<?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 Ezequiel Ortiz Recalde on Medium]]></title>
        <description><![CDATA[Stories by Ezequiel Ortiz Recalde on Medium]]></description>
        <link>https://medium.com/@eortizrecalde?source=rss-2939b50adecd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VnesRW1fsAzQMcqglMGf1g.png</url>
            <title>Stories by Ezequiel Ortiz Recalde on Medium</title>
            <link>https://medium.com/@eortizrecalde?source=rss-2939b50adecd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 19:15:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@eortizrecalde/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[AI Frontiers Series: Human Resources]]></title>
            <link>https://medium.com/data-science/ai-frontiers-series-human-resources-fd245fc0c1c?source=rss-2939b50adecd------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd245fc0c1c</guid>
            <category><![CDATA[business]]></category>
            <category><![CDATA[hr]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[notes-from-industry]]></category>
            <dc:creator><![CDATA[Ezequiel Ortiz Recalde]]></dc:creator>
            <pubDate>Tue, 20 Jun 2023 13:31:44 GMT</pubDate>
            <atom:updated>2023-06-20T21:34:40.128Z</atom:updated>
            <content:encoded><![CDATA[<h4>An introduction to the AI puzzle in untapped territory</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bilW8Y4UTrxVnUYz.png" /><figcaption>Image generated by Author at <a href="https://www.midjourney.com/">Midjourney</a></figcaption></figure><p>Reflecting on my first ‘multi-industry brainstorming session’ nearly three years ago, I’m astounded by how machine learning concepts, once deemed ambitious, are now achievable for HR departments. The rapid pace of AI has been transforming industries, from manufacturing to healthcare. Yet, the Human Resources sector has been slow in embracing this digital revolution.</p><p>While the mix of qualitative and quantitative tasks in HR may suggest it’s an unlikely candidate for AI adoption, this assumption overlooks the potential AI brings to the HR landscape. In this article, we aim to explore this untapped potential. We will focus on the key challenges in the HR industry, significant performance indicators, and how AI technologies can help overcome these challenges. This stands in stark contrast to the limitations of traditional People Analytics solutions.</p><p>Unlike the supply chain data problem discussed in the <a href="https://medium.com/towards-data-science/ai-frontiers-series-supply-chain-f5fa008570ad"><strong>previous article</strong></a>, the primary concern here isn’t just the availability of high-quality data. The processing of this data and adherence to data regulation norms are equally crucial. In the following sections, we will discuss how these factors can be addressed to unlock the transformative power of AI in HR.</p><p>However, before diving into these use cases, it is important to note that your organisation should first assess its readiness to implement these strategies, as recommended by Chowdhury, S., et al., (2023). Plus, as I keep emphasising, checking some broader requirements will surely be of great help (for that you can refer to this <a href="https://medium.com/towards-data-science/14-requirements-to-make-your-machine-learning-project-a-success-part-i-80c288be503d"><strong>article</strong></a>).</p><h3>Challenges in HR Management</h3><p>An easy way to generate valuable ideas is by first understanding the key performance indicators (KPIs) relevant to a specific industry, area, company, etc. Once we have answers for all of them we can start thinking about other “nice to have” solutions. In this regard, all HR departments face the same array of challenges, including <strong>talent acquisition and retention</strong>, <strong>employee engagement</strong>, <strong>performance management</strong>, <strong>diversity and inclusion</strong>, and <strong>regulatory compliance (</strong>Pereira, V., et al., 2023).</p><p>Some typical HR KPIs include:</p><ul><li>time-to-hire</li><li>cost-per-hire</li><li>employee turnover rate</li><li>employee engagement score</li><li>diversity ratios</li></ul><p>It is important to highlight that the processes that these metrics are measuring require a <strong>delicate</strong> <strong>balance of quantitative analysis and human understanding</strong>. Then, to fully comprehend the potential of AI in HR, we must first ask some questions regarding the current state of the processes that are measured by each KPI. Note that this is a standard procedure you should follow while working on any machine learning <a href="https://medium.com/towards-data-science/14-requirements-to-make-your-machine-learning-project-a-success-part-i-80c288be503d"><strong>project</strong></a>. In this sense, we’ll go over each step of the process by using some trigger questions.</p><h4><strong>1. The Talent Acquisition Challenge</strong></h4><p>While hiring new talent, HR professionals need to post a job position, sort through a massive pile of resumes, conduct initial screenings, schedule interviews, and finally, make hiring decisions based on an amalgamation of hard data and soft skills. But do they have the tools to carry out this tasks in an efficient and transparent manner? How can we assert there is no bias in certain processes? Let’s analyse the whole story.</p><p><strong>1.1. Job Position Creation and Posting</strong></p><p>Does your company still write job positions without AI assistance?<em> </em>Following the identification of a hiring need, the initial step of any selection process involves creating and posting a job description on either an owned or a third-party platform such as LinkedIn. Crafting these descriptions can be quite laborious; however, it’s a crucial step to attract top talent and project an image of professionalism in today’s rapidly evolving job market. Furthermore, given the solutions that we’ll be discussing throughout this article, a vague definition of a job position can pose some limitations on the quality of the results we obtain in some use cases (I’ll come back to this soon).</p><p>Job descriptions that are poorly worded can deter qualified candidates, attract unsuitable ones, and complicate the recruitment process. Moreover, they can tarnish a company’s public image by suggesting a lack of professionalism. Vague descriptions might lead to legal complications due to ambiguous job expectations and potentially discriminatory language, infringing equal employment opportunity laws. In contrast, well-drafted job descriptions attract premier talent, expedite hiring, endorse diversity and inclusion, and bolster the company’s reputation. Therefore, organisations must invest sufficient resources in creating thorough, accurate, and inclusive job descriptions, thereby ensuring effective recruitment, legal compliance, and an enhanced public image.</p><p>One straightforward solution is to harness the power of AI text generation. By leveraging cutting-edge tools Large Language Models (LLMs) you can optimise your job description templates and achieve impressive results.</p><p>As an illustration, consider a job position for a senior data scientist specialising in HR with proficiency in AWS. By utilising AI, the prompt could be drafted in less than 10 seconds, proving not just efficient but also highly effective.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B1xeot6nNKvFMJCC_hE7bA.png" /><figcaption>Image by Author</figcaption></figure><p>Note that we can provide a more accurate prompt to reflect the values of the organisation, and the topics that should be evaluated throughout the rest of the recruiting process.</p><p>Following the posting of a comprehensive and engaging job description, it’s natural to see a sizeable pool of candidates and, consequently, a surge in applications. This progression leads us seamlessly into the next phase of the recruitment process: the meticulous and arduous task of resume analysis.</p><p><strong>1.2. Resume Analysis</strong></p><p>Are you still manually sifting through every single resume that lands in your inbox? Is your HR Talent Acquisition Specialist dedicating precious time to analyse hundreds, if not thousands, of applications, even after finding a suitable candidate? Do you ever wonder about the specific variables your recruiters are weighing in their decisions, or how they’re using the resumes left in your database to match candidates with future job postings?</p><p>If these questions have crossed your mind, it’s clear you recognise that the conventional method of manually reviewing resumes and analysing a high volume of applications no longer cuts it in our data-driven age.</p><p>Automated resume parsing solutions have indeed been a significant leap forward, allowing us to extract relevant information from resumes with relative ease. But the buck doesn’t stop here. After the parsing stage, we’re faced with a mountain of data that can feel overwhelming and unwieldy. It’s no longer enough to simply sort this data into tables and run a basic analysis.</p><p>Additionally, while we might assume that leading HR platforms would have mastered the art of resume parsing, the reality is often disappointing. Their performance can be subpar, especially when presented with a resume that deviates from the conventional format, leading to a loss of critical candidate information.</p><p>One solution to overcome these obstacles is <strong>semantic matching</strong>. In machine learning, this concept refers to the process of understanding and comparing the meaning or semantics of different pieces of text or data. It involves assessing the similarity or relatedness between words, phrases, sentences, or even entire documents. The goal is to determine how well different pieces of text align in terms of their underlying meaning, rather than just relying on surface-level patterns or exact word matching. Semantic matching plays a crucial role in various Natural Language Processing (NLP) tasks, such as information retrieval, question answering, sentiment analysis, and text classification. It helps to bridge the gap between the human understanding of language and the computational capabilities of machine learning models.</p><p>How can we use it in this case? By <strong>summarising the job profile</strong> based on the <strong>parsed data</strong> and performing a <strong>semantic match</strong> with the <strong>job position</strong>, a <strong>score</strong> can be generated. This score reflects how well each attribute of the profile aligns with the requirements of the job. Through semantic matching, you can efficiently prioritise and evaluate candidates based on their suitability for the role they applied to (and other roles as well, all in an automated fashion). <strong>Note that the quality of the results can be lacking if the job positions are not well-defined.</strong></p><p>If semantic matching does not sound convincing to you, there are still other alternatives you can explore to address this issue to a significant extent.</p><ul><li><strong>Automated pre-screening</strong>: implement mechanisms that filter out candidates who do not meet specific criteria or minimum qualifications. This can be achieved through rule-based systems or machine learning models trained on historical hiring data. Of course, to do this you should have a parser solution in place.</li><li><strong>ML-based ranking</strong>: develop a ranking system that automatically scores and ranks candidates based on various attributes, such as skills, experience, and qualifications. This approach enables data-driven decision-making and eliminates bias in the evaluation process.</li></ul><p>Note that investing in the implementation of these changes can turn out to be more impactful than you expected. These techniques can benefit your HR operations in several ways:</p><ul><li><strong>Scalability and efficiency:</strong> As businesses scale and receive a higher volume of applications, it becomes increasingly challenging to handle the workload manually. The techniques mentioned can provide scalability by efficiently processing and evaluating a large number of resumes, ensuring a consistent and thorough analysis across all applications. Plus, by automating the initial stages of resume analysis, companies can significantly reduce the time and resources spent on reviewing unqualified candidates. This allows HR teams to focus their efforts on more strategic tasks, such as interviewing and assessing the most promising candidates.</li><li><strong>Reduction of bias</strong>: the implementation of the solutions describe has the much needed potential to reduce bias in the candidate evaluation process. By focusing on the semantic alignment between the job requirements and candidate attributes, the evaluation becomes more objective and less susceptible to unconscious biases that may influence manual resume screening.</li><li><strong>Continuous learning:</strong> Machine learning-based approaches, including can continuously learn and improve over time. By leveraging historical data and feedback from recruiters, these systems can adapt to the organisation’s specific needs, refine their matching algorithms, and become more accurate and effective in identifying the most suitable candidates. Thus, setting the foundations now will certainly yield tenfold benefits in the future.</li></ul><p>Having analysed the resumes, let’s move on to the crucial stage of candidate interviews.</p><p><strong>1.3. Candidate interview 2.0</strong></p><p>During interviews, recruiters often seek assistance to streamline the process and ensure effective communication with candidates. To address this need, our team is developing an innovative app that employs speech-to-text models and advanced algorithms. This app aims to provide real-time support to recruiters during interviews.</p><p>By leveraging the app, recruiters can enhance the structure of interviews and ensure that crucial questions are addressed. The app utilises various elements, including job position descriptions, a list of standard interview questions, candidate resumes, and real-time transcripts of conversations.</p><p>Through the use of LLMs, the app analyses the interview content and generate relevant questions and feedback. Recruiters can customise the frequency at which they receive this assistance, tailoring it to their preferences and needs.</p><p>By offering this app, we aim to optimise the interview process, saving time for both recruiters and candidates while promoting efficient and insightful conversations.</p><p><strong>1.4. End-to-End Automation?</strong></p><p>Are you now planning on a full automation of the recruitment process?<em> </em>Note that I never suggested using AI chatbots or other method to automate the whole recruiting process. Why? Well, I do not think we are at that point yet, and we can benefit much more from keeping the human factor. While automation and advanced techniques can greatly enhance the talent acquisition process, it’s important to recognise the value of human judgment and expertise. Employing a human-in-the-loop approach, where the results of the automated techniques are reviewed and validated by human recruiters, ensures a balanced and accurate evaluation that combines the strengths of both human intelligence and machine learning algorithms.</p><p>As a nice closure, I leave you something to meditate on: if we automate the process using tools such as AI chatbots, the candidates can also use AI to learn how to convince these chatbots in a kind of reinforcement learning process…</p><h4><strong>2. The Talent Retention Challenge</strong></h4><p>Once you’ve managed to hire a candidate, next comes the most important piece of the puzzle, retaining the talent to avoid wasting all the effort put on the hiring process, and avoid the damage that the employee exit could cause to the organisation. Regarding this problem there are several things you could do.</p><p><strong>2.1. Employee Attrition Prediction</strong></p><p>Is your organisation predicting the probability of each of its employees leaving the company in the next quarter/semester/year?<em> </em>Successful employee retention often relies on proactive measures taken before the issue arises. How many times has your organisation made counter offers way too late for an employee to change his/her mind? Probably too many to count. To address this challenge then, it is crucial to detect employees at a high risk of leaving the organisation before they reach that point.</p><p>In this context, glass-box machine learning models can be developed to predict the likelihood of an employee leaving within the next <em>n</em> months and identify the factors contributing to this probability. Unlike black-box models, glass-box models offer interpretability, enabling a clear understanding of the reasons behind the predictions. This distinction is crucial because we are dealing with sensitive employee data, and the actions recommended by the model’s inferences could significantly impact an employee’s career trajectory. Therefore, complete transparency and understanding of the model’s workings are paramount.</p><p>With this in mind, my colleagues and I have developed a model that addresses the shortcomings commonly observed in mainstream “solutions” of this issue. To go into the technical details of how to approach this problem following a correct framework, I recommend referring to this <a href="https://medium.com/towards-data-science/cracking-the-employee-attrition-problem-with-machine-learning-6ee751ec4aae"><strong>article</strong></a>.</p><p><strong>2.2. Personalised Employee Development</strong></p><p>Is your organisation offering a custom professional path?<em> </em>Employees often seek a balance between competitive compensation and opportunities for professional growth. While both aspects are desirable, younger professionals, for instance, may prioritise the chance to develop their skills and advance in their chosen field. By recognising this, organisations can leverage personalised learning and development plans to enhance employee retention by fulfilling their part of the unspoken bargain.</p><p>AI-powered recommendation systems can play a significant role in this regard. These systems leverage employee performance data and analyse individual strengths, weaknesses, and career goals. They also consider information from “similar” employees who have achieved success in similar roles or career paths. By integrating these insights, organisations can create tailored recommendations for training and “upskilling” opportunities that align with each employee’s specific needs and aspirations.</p><p>Additionally, on the mainstream side, AI-powered recommendation systems can provide ongoing guidance by suggesting relevant learning materials, courses, mentorship opportunities, or networking events that align with each employee’s development plan. By adapting to individual preferences and evolving career paths, these systems ensure that employees have access to relevant and engaging learning experiences throughout their journey with the organisation.</p><p>Next, tightly linked to the retention issue we have the engagement problem.</p><h4>3. The Employee Engagement Challenge</h4><p>Employee engagement, a measure of an employee’s emotional and physical commitment to their work environment, is critical to an organisation’s success. It contributes to higher performance, job satisfaction, and retention rates. Currently, engagement is typically gauged alongside job satisfaction through periodic surveys, but this approach falls short in two ways:</p><ul><li><strong>Frequency</strong>: The infrequent nature of these surveys results in outdated snapshots of engagement.</li><li><strong>Complexity</strong>: These assessments often require multi-dimensional analyses that are challenging for humans to perform accurately.</li></ul><p>To tackle these issues, we propose an approach that considers the organisation as a network of interacting nodes, providing a holistic perspective.</p><p><strong>3.1. Organisational Network Analysis</strong></p><p>Organisational Network Analysis (ONA) uses techniques from graph theory to systematically explore and understand an organisation’s network, including management structures, interpersonal relationships, and information flow (Barabási, A. L., 2013).</p><p>To implement ONA, the network is constructed either through nomination surveys or using digital footprints from workspace platforms (mindful of data protection considerations). After establishing the network, traditional graph algorithms can be employed to determine the centrality of each member and their influence within the organisation. These metrics, combined with employee characteristics and past survey insights, can then be used to develop a model predicting employee engagement.</p><p>By leveraging ONA, organisations can gain valuable insights into their internal dynamics, identify key influencers, assess each individual’s role, and predict employee engagement levels. However, it is imperative to ensure data privacy and protection throughout the process. Strict compliance with data protection agreements and ethical considerations should be maintained during data collection and analysis.</p><p><strong>Note that ONA is not AI</strong>… but a first step to gather relevant data in a functional way that will allow us to create or add to our current model developments. For example, we could extract valuable data about the interaction or connectivity levels within the organisation and use this information as features for the attrition model or and engagement model that aims to predict the level of engagement within an organisation at any given time. For those interested in getting a more detailed explanation of this topic I recommend you to refer to this <a href="https://medium.com/towards-data-science/an-introduction-to-organizational-network-analysis-cfa91a0e2fda"><strong>article</strong></a>.</p><p><strong>3.2. AI Engagement Assistants</strong></p><p>Have you considered extracting both quantitative and qualitative insights from written satisfaction forms? AI can play a pivotal role here. Rather than creating AI assistants to monitor employees — which risks devaluing the human factor — we propose using them to solicit anonymous feedback on company improvement opportunities. This feedback can be analysed and structured for the HR department to extract actionable insights, akin to the function of the earlier proposed interview assistant.</p><p>This approach can also be valuable for more specific tasks. For instance, when seeking feedback on workshops, instead of using traditional 1 to 5 scale surveys, attendees could be encouraged to provide detailed written feedback. This qualitative data can be analysed using LLMs to uncover deeper, more meaningful insights.</p><p>Although written feedback might sometimes lack quality and specificity, the rich context it provides makes it a worthy avenue for exploration.</p><p>Next, we explore the interconnected challenges of engagement, retention, and performance management.</p><h4>4. The Performance Assessment Challenge</h4><p>Traditional performance assessment processes often face issues related to uneven quality, incompleteness, and time consumption.</p><p>Uneven quality: arises from varied writing skills and communication abilities among managers when providing feedback. Poorly constructed or unclear feedback can fail to impact employees positively, failing to address areas for improvement or recognise achievements effectively.</p><p>Incompleteness stems from overlooked achievements or areas for improvement during the assessment period. This lack of comprehensive feedback may result in missed opportunities for guiding employees towards better performance or acknowledging their successes.</p><p>The process of crafting thorough performance reviews is time-consuming, which can divert managers’ valuable time away from more productive activities, such as coaching or mentoring employees.</p><p>These challenges necessitate an efficient, streamlined approach to performance assessments that optimises resource utilisation, ensures fairness, and enhances the quality and completeness of feedback.</p><p><strong>4.1. Assessment Assistant</strong></p><p>For those grappling with remembering key details while conducting multiple employee reviews, a solution might be in leveraging summarisation models. In fact we’ve built a <a href="https://www.linkedin.com/posts/javierdelgado_thinkhuman-workdigital-activity-7061958057412415488-qy5F?utm_source=share&amp;utm_medium=member_desktop"><strong>solution</strong></a> for this problem.</p><p>Imagine we have an organisation named “TheBestCompany”. In TheBestCompany, they utilise LLMs models to process multiple data sources and generate employee reviews. Various data sources like feedback, participation in initiatives, and customer feedback are compiled and fed into the LLM, which then distinguishes between achievements and improvement areas and consolidates this feedback into a performance review template that can then be modified by the current human reviewer.</p><p>This automated review generation process saves time and resources, minimises bias and errors, and generates detailed and accurate reviews. The flexibility of LLMs allows customisation based on organisational needs, enhancing the accuracy, efficiency, and fairness of performance assessments. This solution enables organisations to focus on other important tasks and objectives.</p><h4>5. Tackling the Diversity and Inclusion Challenge</h4><p>Diversity and inclusion pose enduring challenges within many organisations, extending beyond the hiring process to include promotions and performance appraisals. Subjectivity in these areas can unintentionally obscure the merits of one employee and the shortcomings of another (Rodgers, W., et al., 2023).</p><p>Two strategies can help mitigate this. The first involves developing algorithms that dismiss sensitive variables such as age, gender, ethnicity, and religion. These algorithms, focusing on qualifications, skills, and performance, encourage objective evaluations that can reduce biases and ensure fair decisions.</p><p>The second strategy utilises models that account for these sensitive variables to understand their impact on certain outcomes. Analysing historical data, these models can reveal potential biases associated with specific attributes, helping organisations to proactively identify and rectify systemic issues, fostering equal opportunities and inclusivity.</p><p>However, it’s crucial to remember that algorithms and models should supplement human judgement and expertise, not replace them. Moreover, these tools should be regularly audited to ensure they don’t unintentionally perpetuate biases.</p><h4>6. The Data Quality Challenge</h4><p>Data quality is a frequent obstacle in HR, with manual inputs leading to potential errors, inconsistent formatting, or incomplete records in HR platforms like Workday or SAP HR. These issues can compromise the accuracy and reliability of machine learning algorithms, encapsulated by the phrase, “Garbage In, Garbage Out”. Implementing a meticulous ETL (Extract, Transform, Load) process is, therefore, vital for data integrity, bearing in mind ethical considerations and the impending data protection challenge. In fact, almost 90% of the time destined to the development of all the use cases mentioned through out this article should be spent on the ETL process.</p><h4>7. The Data Protection Challenge</h4><p>HR data often includes sensitive personal information, requiring robust data protection measures. To safeguard this data, organisations must employ strong data governance practices, including stringent security measures, access controls, and data encryption techniques (Hamilton, R. H., &amp; Davison, H. K., 2022).</p><p>It is essential to establish clear policies for data handling, storage, and sharing, granting access only to authorised personnel. By prioritising data protection and adhering to legal regulations, organisations can build trust with employees while preserving the privacy and confidentiality of HR data.</p><p>Working closely with legal and compliance teams is also necessary to meet all applicable laws and regulations, especially specific data protection laws like the GDPR in the EU. In all these processes, it’s important to seek legal counsel and advice from data protection professionals to ensure compliance with local laws and regulations.</p><h3>Concluding Remarks</h3><p>All in all, we have seen that the intersection of AI and HR opens a realm of possibilities that are waiting to be explored. In this scenario, the challenge for data scientists and business professionals is to translate these possibilities into tangible solutions that streamline HR processes while preserving the valuable human element. It involves both harnessing AI’s power and understanding the subtleties of HR management. Without a doubt this balance will drive the future, creating a more effective, inclusive, and empathetic HR industry.</p><p>Stay tuned for more insightful articles in this series as we endeavour together to improve the world through the democratisation of innovative solutions.</p><h3>References</h3><p>[1] Chowdhury, S., Dey, P., Joel-Edgar, S., Bhattacharya, S., Rodriguez-Espindola, O., Abadie, A., &amp; Truong, L. (2023). Unlocking the value of artificial intelligence in human resource management through AI capability framework. <em>Human Resource Management Review</em>, <em>33</em>(1), 100899.</p><p>[2] Pereira, V., Hadjielias, E., Christofi, M., &amp; Vrontis, D. (2023). A systematic literature review on the impact of artificial intelligence on workplace outcomes: A multi-process perspective. <em>Human Resource Management Review</em>, <em>33</em>(1), 100857.</p><p>[3] Barabási, A. L. 2013. Network science. <em>Philosophical Transactions of the Royal Society A: Mathematical, Physical and Engineering Sciences</em>, 371(1987), 20120375.</p><p>[4] Rodgers, W., Murray, J. M., Stefanidis, A., Degbey, W. Y., &amp; Tarba, S. Y. (2023). An artificial intelligence algorithmic approach to ethical decision-making in human resource management processes. <em>Human Resource Management Review</em>, <em>33</em>(1), 100925.</p><p>[5] Hamilton, R. H., &amp; Davison, H. K. (2022). Legal and ethical challenges for HR in machine learning. <em>Employee Responsibilities and Rights Journal</em>, <em>34</em>(1), 19–39.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd245fc0c1c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/ai-frontiers-series-human-resources-fd245fc0c1c">AI Frontiers Series: Human Resources</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[AI Frontiers Series: Supply Chain]]></title>
            <link>https://medium.com/data-science/ai-frontiers-series-supply-chain-f5fa008570ad?source=rss-2939b50adecd------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5fa008570ad</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[business]]></category>
            <category><![CDATA[supply-chain]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[notes-from-industry]]></category>
            <dc:creator><![CDATA[Ezequiel Ortiz Recalde]]></dc:creator>
            <pubDate>Tue, 06 Jun 2023 05:40:03 GMT</pubDate>
            <atom:updated>2023-09-22T06:12:21.681Z</atom:updated>
            <content:encoded><![CDATA[<h4>An introduction to the current use cases and possibilities in a gigantic industry</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F2YTbTm4NT5XQLUy.png" /><figcaption>Image by Author generated at <a href="https://www.midjourney.com/">Midjourney</a></figcaption></figure><p>Recently, I’ve pondered how I can provide equal value to both technical and business-oriented professionals in my writings. Fortunately, my role as a data science consultant naturally offers a wealth of interesting topics. Beyond coding, we consistently review literature and articles detailing data-driven solutions across various sectors. This continuous exploration enables us to evaluate the feasibility, efficiency, and effectiveness of these solutions, leading us to either employ existing strategies or craft bespoke algorithms.</p><p>This article marks the beginning of a series aimed at illuminating the primary challenges, standard solutions, as well as emerging opportunities and risks in three pivotal sectors: supply chain, human resources, and retail. It is aimed at professionals within these industries looking for data-driven solutions, as well as fellow data scientists interested in broadening their scope. As the title suggests, our first stop is the complex world of supply chain management.</p><p>From managing intricate logistics networks to accurately forecasting demand and optimising inventory, the supply chain ecosystem presents numerous formidable challenges. One of the hardest ones to solve is the seamless coordination and optimisation of operations amidst an intricate network of diverse stakeholders such as suppliers, manufacturers, distributors, retailers, and customers. Furthermore, constant disrupters such as fluctuations in raw material availability, market demand, geopolitical tension, and environmental catastrophes pose additional difficulties.</p><p>What can we do about them? Well, thanks to recent advancements in AI, we have exciting opportunities to provide better answers to these issues. Throughout this article, we’ll draw on our experience and referenced studies to briefly describe challenges and current/potential solutions that could help you take your operations to the next level.</p><h3>Challenges in Supply Chain Management</h3><p>All supply chain management problems have their roots in the search of the supply and demand equilibrium. Someone demands (offers) a good at a certain price, and for this demand (offer) to be satisfied (sold), the price or relevance of the product should be attractive enough. This over summarised dynamic that you learn in any economy introductory course develops into one of the most complex problems to solve. As it is quite easy to get lost in the broadness of the issue, we’ll start from somewhere close to the beginning.</p><h4>1. The Inventory Management Problem</h4><p>Efficient inventory management remains an essential part of supply chain operations. Mismanagement can tie up substantial capital, increase carrying costs, and risk obsolescence. Conversely, inadequate inventory can potentially lead to missed sales opportunities, loss of customer trust and even death (on shortage of medical supplies). Striking the optimal balance thus becomes a significant challenge.</p><p>In order to tackle this challenge we first must anticipate the demand and then act in accordance.</p><p><strong>1.1. Demand forecasting</strong></p><p>Precise demand forecasting is vital to ensuring that the right products are available at the right place and at the right time. However, demand is influenced by a multitude of factors including seasonal trends, market shifts, and unforeseen events, complicating the task of accurate forecasting. Fortunately, machine learning algorithms can be trained on historical sales data, market trends, and other pertinent factors to predict future demand. For example, Amazon uses complex demand forecasting models to optimise its inventory. They leverage vast amounts of data collected from their sales, including historical sales data, special events, holidays, and even weather forecasts. For instance, they’ve used machine learning models to predict the demand for different products during events like Black Friday, allowing them to stock up on high-demand items and avoid stock-outs or overstocking. Furthermore, Amazon uses machine learning to optimise its warehouses, positioning products based on demand to reduce the time taken to pick items for an order. The good news? You don’t have to be Amazon-sized to achieve this. Anyone with a transactional database and willingness to invest in cloud services can do the same.</p><p>But what model should we choose? Let’s check on what the industry is doing to solve the forecasting problem.</p><p><strong>Forecasting solutions</strong></p><p>Here, most businesses operate by using one of the following:</p><ul><li><strong>Simple statistics</strong>: any form of <strong>mean or median predictions</strong>. Could be used as benchmarks to compare the performance of machine learning models, but these are not smart forecasts as we are assuming that the time window chosen to calculate the mean is a good estimate of the mean of future values. This could work for low variance and static series, but when we have seasonality problems and special events we’ll end up messing things up.</li><li><strong>Classic time series models</strong>: <strong>autoregressive models</strong> (ARIMA, SARIMA, SARIMAX, VAR<em>, </em>etc) or <strong>exponential smoothing</strong> (Holt-Winters), which may deliver good results when the series are stable i.e. they have low variance and clear trends. Of course, these are better than using simple statistics yet they do not leverage the full potential of the features that characterise each time series and additional information that could be extracted from similar series (for example, products with similar sales and characteristics). Additionally, in case you have thousands of series composed by store-product combinations, the fitting process of these models will become a gruesome one.</li><li><strong>Ensemble/Boosting algorithms</strong>: models such as <strong>Random Forest</strong>, <strong>CatBoost</strong>, <strong>XGBoost</strong> and <strong>LightGBM</strong>. In this regard, it is important to highlight that these models aren’t specifically designed to handle time-series data, especially when it comes to multistep or multi-horizon forecasting, where each prediction should take into account previous predictions. In short, time-series data often contain temporal dependencies, which these algorithms <strong>do not explicitly model</strong>. Using these methods for multistep forecasting would involve predicting one step at a time and using each prediction as an input for the next prediction (i.e. recursive forecasting). This approach, however, can accumulate errors as predictions are propagated forward... So even if this is accounted for, the procedure remains conceptually flawed and suboptimal. Moreover, as in the case of classic time series models, we’ll face a real problem when trying to train on thousands of series composed by store-product combinations, as these models lack the ability to learn the specifics within such a wide variety of classes.</li></ul><p>As you can guess we do not believe that these methods could work in complex scenarios where we have millions of observations, lots of series, and high volatility. This is where <strong>Deep Learning Models</strong> can offer a significant advantage provided you have enough quality data and computational power.</p><p>In this regard, we can implement neural networks that are designed to handle sequences of data, making them better suited for tasks like multi-horizon forecasting where the prediction of future values depends on past and present inputs. The most famous ones are:</p><ul><li><strong>Recurrent Neural Networks (RNNs): </strong>designed to recognise patterns in sequences of data, such as text, genomes, handwriting, or the time series data used in forecasting. They are called “recurrent” because they perform the same operation for every element of a sequence, with the output being dependent on previous computations. This allows them to maintain information in “memory” over time. However, they can struggle with maintaining this “memory” over long sequences.</li><li><strong>Long Short-Term Memory (LSTM)</strong> <strong>networks</strong>: a special kind of RNN, capable of learning long-term dependencies. LSTMs were designed to combat the “vanishing gradient” problem in traditional RNNs, which made it hard for the networks to maintain their “memory” over long sequences. The key to LSTMs is the cell state, a horizontal line running through the top of the diagram (if you’ve ever seen a schematic of an LSTM). The cell state can carry information throughout the processing chain with minimal changes, which is what allows LSTMs to transport “memory” down the sequence chain. This makes them particularly effective for tasks where the prediction of future values depends on past and present inputs.</li></ul><p>In short, RNNs and LSTMs are suited for time series forecasting due to their ability to process sequence data and maintain “memory” over time. However, LSTMs, with their unique architecture, have a better capability to handle long-term dependencies in the data, making them a preferred choice for complex forecasting tasks.</p><p>In this regard, I’ve found recent success with the <strong>Temporal Fusion Transformer (TFT)</strong> model to forecast the daily demand of a multitude of products (+400) across various stores (+50) by just using the information that describes each time series (sales, price, product category/subcategory, month, weekday, weekend, discount percentage, store_id, store location, product_id, time_idx, special days, relative_time_idx and rolling averages). If there is enough interest I may write an article on the full implementation, until then, here’s the <a href="https://arxiv.org/abs/1912.09363"><strong>paper</strong></a>. In any case, I believe that at the moment this is the most powerful predictive tool for multi-horizon forecasting.</p><p>Here are some of its main advantages that make it clear how deficient the other approaches are.</p><ol><li><strong>Handling Multiple Time Series:</strong> TFT can work with multiple time series data, which is a critical factor when you need to forecast demand for a large number of products across different stores. Each product and store may have their own unique characteristics and time-series patterns, such as seasonality, trends, and other factors. TFT is capable of capturing these patterns for each individual time series, enabling more accurate and personalised predictions. Note that this is one of the problems that boosting algorithms does not manage to deal with correctly.</li><li><strong>Flexible Incorporation of Static and Dynamic Covariates:</strong> TFT can incorporate different types of covariates in the forecasting model. For instance, information about each store (like location, size, and customer demographic) and each product (like category, subcategory, price, and promotional activities) can be fed into the model as static covariates. Similarly, dynamic covariates like special events, weather, or changing economic conditions can also be incorporated.</li><li><strong>Non-linear and Complex Temporal Dependencies:</strong> TFT is particularly adept at capturing complex temporal dependencies and non-linear relationships in the data. It uses attention mechanisms to identify and weigh important historical information. It allows the model to learn what information from the past is most relevant for forecasting future values. Note that this comes as a solution to one of the most common issues with forecasting i.e. choosing which time window is relevant to predict the next sequence of values.</li><li><strong>Probabilistic Predictions:</strong> One of the key advantages of TFT is that it can provide probabilistic forecasts. This is particularly important in demand prediction, where understanding uncertainty can guide decision making. For example, knowing the range within which the demand is expected to lie (with a certain probability) is very useful in determining stock policies, such as safety stock levels, and avoiding stockouts or overstocking. This is done by using a <strong>QuantileLoss</strong> function instead of the commonly used performance metrics such as RMSE, MAE, MAPE, SMAPE, etc.</li><li><strong>Interpretability:</strong> Despite being a “black-box” model, TFT has mechanisms for interpretability. The attention mechanisms in the model can provide insights about what historical inputs are important for the prediction and how different covariates contribute to the forecast. This can be important in business scenarios where understanding the reasons behind a prediction is as important as the prediction itself. In the example mentioned, we use this to do a manual debugging of the model, to check for inconsistencies or “badly” trained models. For instance, we found that the special days needed some tuning as the days directly before the special days were more relevant that the special days per se (movement from the city centers began the day before).</li><li><strong>Scalability:</strong> Lastly, TFT is also designed to be computationally efficient. It uses variable selection networks to reduce the dimensionality of the data, making it feasible to scale to large numbers of time series. This makes it quite suitable for a scenario like the one we mentioned, where we have to predict the demand for hundreds of products across dozens of stores.</li></ol><p>I advise you to check the implementation of TFT and more advanced models in the <a href="https://pytorch-forecasting.readthedocs.io/en/stable/"><strong>pytorch-forecasting documentation</strong></a>.</p><p><strong>1.2. Inventory optimisation</strong></p><p>So, once we forecast the demand for the next operating period, we must determine the best way to acquire the goods/components required to meet that demand. But where do we start? We can begin by identifying everything that needs to be analysed to achieve the best outcome. For instance, a list of variables could include:</p><ul><li><strong>Supplier alternatives and costs</strong>: How many suppliers do I have, and how much do they charge me for each unit provisioned?</li><li><strong>The presentation of the product</strong>: you may have predicted that you are going to sell 120 candies but these come in boxes of 60, so you need to convert all units into their deliverable version.</li><li><strong>Warehouse capacity</strong>: How much stock can my warehouse accommodate?</li><li><strong>Delivery times</strong>: By what date and time do I need to receive the stock to avoid a goods shortage?</li><li><strong>Lead times</strong>: How long does each supplier take to deliver the order after it has been placed?</li><li><strong>Order times</strong>: What dates does the supplier accept and deliver orders? A supplier may only deliver on specific days of the week.</li><li><strong>Security stock</strong>: What’s the policy regarding the minimum stock of a product at each warehouse?</li><li><strong>Store locations</strong>: Where do the goods/components need to be delivered?</li><li><strong>Load transportation method:</strong> How will the orders be delivered and what characteristics are associated with that decision?</li></ul><p>After considering these factors, it’s time to build a model. This is where data science extends beyond merely running code implementations. We’ll need to combine domain knowledge, technical skills, and creativity to work within the unique framework of <strong>Linear Programming</strong> and <strong>Mixed Integer Programming</strong> (or alternatively heuristics and meta-heuristics).</p><p>I’ve already written an <a href="https://medium.com/towards-data-science/fleet-and-workforce-planning-with-linear-programming-16db08c7f91d"><strong>article</strong></a> on this topic where a real life problem is presented, so I won’t go into the details. However, the point is that these methods can help us to maximise/minimise an outcome (utility function) based on several types of restrictions (for example, warehouse capacity, number of trucks, workers) and a cost function (variable and fixed costs per transportation method, cost per driver, cost per supplier, etc). The main strength and weakness of this framework is that you must define the problem you want to solve:</p><ul><li>If you lack creativity, domain knowledge, and technical skills, you might fail to specify the problem;</li><li>But, the more knowledgeable you are, the more likely it is that you will end up defining a highly specific problem that becomes computationally unsolvable.</li></ul><p>In any case, it’s always better to be in the latter scenario, as you can always reduce the problem specification. Building on this, the concept of inventory optimisation leads us into the broader problem of supply chain network optimisation.</p><h4><strong>2. </strong>The Supply Chain Network Optimisation Problem</h4><p>Optimising the supply chain network is a multi-faceted challenge where we start by assuming/forecasting a certain demand and then determine the most efficient routes, modes of transportation, and storage facilities of different goods. In terms of transportation, these issues can be further classified based on whether they involve unimodal or intermodal logistics.</p><ul><li><strong>Unimodal logistics:</strong> involves the use of a single mode of transportation, such as land, sea, or air. Each mode presents unique challenges — land transportation can face traffic congestion or road infrastructure issues, sea freight is subject to weather conditions and port capacity, and air freight involves considerations like airspace restrictions and fuel costs. Each mode requires specific types of variables and a unique problem definition. For example, an interesting problem in land transportation would be optimising the transportation of loads across the country based on the type of equipment (e.g. van, reefer or flatbed), driver preferences (perhaps some states are to be avoided), time windows for pickup and delivery, and work restrictions (like mandatory rest periods for drivers);</li><li><strong>Intermodal logistics: </strong>involves coordinating multiple modes of transportation, such as using trucks and ships for the same journey. This adds an extra layer of complexity as it requires seamless coordination between different modes of transportation and handling goods during the transfer from one mode to another. Given these complications, we could either tackle each problem separately or strive to provide a global optimum, which would result in a large model with several assumptions that may or may not be sufficiently accurate. In this case, the best approach might be to bring all the experts or actors involved in each stage, draft the problem as accurately as possible, and then prune non-essential elements.</li></ul><p>Once again, algorithms such as Linear Programming and Mixed Integer Programming can be employed to find partial solutions to the problems that arise when analysing unimodal and intermodal businesses. However, given the potential size and complexity of the problem, heuristic and meta-heuristics algorithms like <strong>Genetic Algorithms</strong> may be more suitable.</p><p>From my experience (just in unimodal logistics), the best approach to complex problems, like the <strong>Capacitated Vehicle Routing Problem</strong> with <strong>work</strong> and t<strong>ime window constraints</strong>, is to use a combination of heuristics, traditional graph theory algorithms, and a well-designed data processing procedure (smart filtering and vectorised operations). This approach narrows down the solution search space, enabling us to sidestep the computation of unfeasible or suboptimal combinations of outcomes, and more important than anything: to obtain a solution within a reasonable amount of time.</p><p>One important caveat though: these specific solutions often remain unpublished, forming part of the strategic algorithms that offer a competitive edge to a company. So, the main takeaway here is that before rushing to implement a solver from a package like Google OR-Tools, consider whether you could achieve sufficient results using heuristics/meta-heuristics, graph algorithms, and intelligent data processing. This approach could offer a more manageable and equally effective solution to your supply chain network optimisation challenges.</p><h4>3. The Risk Management Problem</h4><p>Supply chains are susceptible to a wide array of risks, from natural disasters to geopolitical unrest and market volatility. Identifying, assessing, and mitigating these risks are significant challenges within supply chain management.</p><p><strong>3.1. Potential solutions</strong></p><p>As recent studies suggest, there’s still much to be done regarding Supply Chain Risk Management (Ganesh, A. D., &amp; Kalpana, P. , 2022). With this in mind, I summarise some of the developments possibilities that are being discussed:</p><ul><li><strong>Harnessing NLP for Proactive Risk Monitoring</strong>: Recent Natural Language Processing (NLP) models like GPT, among others, can be used to scrutinise news articles and social media posts for potential supply chain threats. This information can generate personalised alerts and devise corresponding mitigation strategies. Coupled with advanced analytics, this could offer predictive insights into impending market turbulence, enabling proactive risk management. To illustrate, consider creating a bot using the OpenAI GPT API to monitor specific media channels. It can extract pertinent data from news articles and social media posts and use the GPT model to determine if an event may impact your operations. For instance, during the <a href="https://www.bbc.com/news/business-56559073">Suez Canal blockage</a> in 2021, a well-configured NLP system would have identified the event and alerted relevant stakeholders to begin considering alternative routes or modes of transportation.</li><li><strong>Evaluating Performance with NLP &amp; Forecasting Tools:</strong> The same NLP tools, combined with graph theory, forecasting, and classification models, can evaluate, categorise, and recommend Suppliers/Shipper/Driver based on their historical performance. This contributes to supply chain efficiency and transparency, enabling underperforming entities to be identified and potentially replaced. Consider a model that assesses a supplier’s history of delivery timeliness, product quality, and responsiveness. This can help identify whether they are a reliable partner or if sourcing alternatives should be considered.</li><li><strong>Predictive Maintenance Models: </strong>Predictive models allow us to forecast machinery and equipment issues, enhancing preventative maintenance measures. This could reduce downtime, cut costs, and extend equipment lifespan. For example, a predictive model might analyse historical data on a fleet of delivery trucks to anticipate when certain components are likely to fail, helping to schedule preventative maintenance and avoid unexpected breakdowns.</li><li><strong>Geospatial Analysis for Geographical Risks:</strong> Geospatial analysis can elucidate and evaluate geographical risks in the supply chain, such as a warehouse located in a flood-prone area, allowing for better contingency planning.</li><li><strong>Leveraging IoT and Blockchain for Real-time Monitoring and Predictions:</strong> Pairing IoT and Blockchain technology data with predictive models can boost real-time monitoring and tracking capabilities. Moreover, it can enable real-time deviation predictions, accompanied by alerts and mitigation strategies. This improves transparency and traceability, diminishing risks tied to fraud, counterfeiting, and non-compliance. (Kaur, A., et al., 2022).</li></ul><p><strong>3.2. What can be done while studying potential solutions</strong></p><p>Based on what I’ve seen, I cannot stop emphasising that organisations should invest more resources in developing simulations to understand the potential impacts of various strategic decisions. The best thing? You don’t need more than pure Python and domain knowledge.</p><p>Consider a hypothetical retail company “TheRetail”. TheRetail is considering whether to centralise their supply management through a single logistics operator, or maintain direct relationships with multiple suppliers. To evaluate this decision, they could run simulations to assess the potential impacts of each option. These should, at the minimum, consider factors like cost efficiency, delivery speed, flexibility, and vulnerability to disruptions. Let’s imagine some scenarios:</p><p><strong>a)</strong> simulate a situation where the logistics operator faces a significant delay or shutdown. How long could TheRetail maintain operations using their current inventory? How would this impact their sales and customer satisfaction?</p><p><strong>b)</strong> consider the impact of a supplier shutting down or raising prices. Could the logistics operator quickly find a replacement? How would this compare to TheRetail’s ability to switch suppliers in their current system?</p><p>These are just simple examples to showcase that by running thousands or even millions of scenarios any company can gain a better understanding of the potential risks and benefits associated with each strategy, while allowing for better informed decisions.</p><p>Up to know we discussed about solutions but have not mentioned why is it that there is still so much to do. Don’t worry, we’ll go over that next.</p><h4>4. The Data Problem and the Future of Supply Chain</h4><p>Thus far, we have outlined the three main challenges in supply chain management — inventory management, supply chain network optimisation, and risk management. These issues coexist and interplay, creating a complex landscape. The key to navigating this landscape and addressing these challenges lies in the realm of data. Specifically, we require <strong>systematic, clean data adhering to a unified taxonomy</strong>. As probably more than one angry logistics manager has stated, “The era of managing supply chains via excel spreadsheets must end…”</p><p><strong>4.1. Deciphering the Data Puzzle</strong></p><p>It is no surprise then that a data-centric approach is indispensable for tackling these challenges. What this implies is that we need to account for a spectrum of data sources, encompassing but not restricted to: Historical sales data for demand forecasting; Current inventory levels and their locations; Supplier performance data; Transportation costs and delivery times; Market trends and customer behaviour data; Geopolitical data and news updates for risk assessment; Equipment usage data.</p><p>Overcoming data acquisition and integration challenges can be done by implementing a robust data infrastructure that can handle large volumes of diverse data types. Moreover, partnering with data providers or enhancing internal data collection processes can address data scarcity issues.</p><p>Beyond mere data acquisition, we must also ensure our ability to interconnect this data in a coherent and logical manner. In other words, we need a clear database schema, outlining distinct entities and their relationships. Essentially, we need to realise End-to-End (E2E) Supply Chain Visibility and consolidate this wealth of information into a consistent database — a monumental challenge. However, there are individuals brave (or audacious) enough to confront this task and catalyse a new era in supply chain management: The era of End-to-End Supply Chain Visibility. But what does this concept refer to?</p><p><strong>4.2. The Future — End-to-End Supply Chain Visibility</strong></p><p>End-to-End (E2E) supply chain visibility is a transformative concept in the industry. It mandates a comprehensive, transparent view of all processes and data from the inception to the conclusion of the supply chain. Accomplishing this comprehensive visibility involves navigating multiple actors, intricate processes, and vast data points. (Dolgui, A., et al., 2022).</p><p>Yet, by integrating Artificial Intelligence (AI) throughout the supply chain, we can exploit advanced analytics and machine learning capabilities. These AI-powered technologies interpret and contextualise the vast data generated by supply chain activities, offering invaluable insights and enhancing visibility across the entire chain. In doing so, they establish the groundwork for complete transparency.</p><p>As you can guess, AI not only enables end-to-end transparency but also flourishes in such an environment. With transparency in place, and access to all the relevant data, models operate more efficiently, delivering more accurate and valuable outputs. This synergistic dynamic ultimately fosters a more proactive approach to supply chain management. Once this full transparency is achieved, everything we talked about in the previous section becomes much easier to make a reality.</p><h3>Concluding Remarks</h3><p>This overview provides a glimpse into the transformative potential of AI and data science technologies in the supply chain industry. By tackling long-standing challenges, these technologies promise to shape a future of enhanced efficiency, resilience, and responsiveness in supply chains. As we stand on the brink of this exciting frontier, we invite you, our readers and fellow pioneers, to continue exploring and embracing the convergence of data science and supply chain management.</p><p>Stay tuned for more insightful articles in this series as we endeavour together to improve the world through the democratisation of innovative solutions.</p><h3>References</h3><p>[1] Dolgui, A., &amp; Ivanov, D. (2022). 5G in digital supply chain and operations management: Fostering flexibility, end-to-end connectivity and real-time visibility through internet-of-everything. <em>International Journal of Production Research</em>, <em>60</em>(2), 442–451.</p><p>[2] Ganesh, A. D., &amp; Kalpana, P. (2022). Future of artificial intelligence and its influence on supply chain risk management–A systematic review. <em>Computers &amp; Industrial Engineering</em>, 108206.</p><p>[3] Kaur, A., Singh, G., Kukreja, V., Sharma, S., Singh, S., &amp; Yoon, B. (2022). Adaptation of IoT with blockchain in Food Supply Chain Management: An analysis-based review in development, benefits and potential applications. <em>Sensors</em>, <em>22</em>(21), 8174.</p><p>[4] Lim, B., Arık, S. Ö., Loeff, N., &amp; Pfister, T. (2021). Temporal fusion transformers for interpretable multi-horizon time series forecasting. <em>International Journal of Forecasting</em>, <em>37</em>(4), 1748–1764.</p><p>[5] Sharma, R., Shishodia, A., Gunasekaran, A., Min, H., &amp; Munim, Z. H. (2022). The role of artificial intelligence in supply chain management: mapping the territory. <em>International Journal of Production Research</em>, <em>60</em>(24), 7527–7550.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5fa008570ad" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/ai-frontiers-series-supply-chain-f5fa008570ad">AI Frontiers Series: Supply Chain</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[Balancing Machine Learning and Data Privacy]]></title>
            <link>https://medium.com/@eortizrecalde/balancing-machine-learning-and-data-privacy-8735373977c?source=rss-2939b50adecd------2</link>
            <guid isPermaLink="false">https://medium.com/p/8735373977c</guid>
            <category><![CDATA[regulation]]></category>
            <category><![CDATA[business]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-protection]]></category>
            <dc:creator><![CDATA[Ezequiel Ortiz Recalde]]></dc:creator>
            <pubDate>Tue, 30 May 2023 07:30:56 GMT</pubDate>
            <atom:updated>2023-06-27T15:37:15.333Z</atom:updated>
            <content:encoded><![CDATA[<h4>A quick reminder of the relevance of data protection when working with data from users</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sSzMte-47DvJMinq.png" /><figcaption>Image generated by Author at <a href="https://www.midjourney.com/app/">Midjourney</a></figcaption></figure><p>While working in machine learning projects, sooner or later we’ll stumble upon issues regarding data protection that should be taken seriously. However, even when one tries to address them, complying with what is expected can be quite the challenge due to the lack of specifications in their definitions of what is acceptable and what isn’t. This is completely reasonable as data pipelines are quite complex to regulate, but the problem is that this lack of specification leaves us with an unclear guide of what exactly needs to be done to handle the data in a compliant manner. Despite this, it is clear that we still need to comply with them.</p><p>So what can we do to avoid making simple mistakes? <strong>The purpose of this article is to remind the reader about the importance of the topic, and answer the main question while providing some suggestions to stay away from future problems.</strong></p><p>To do so we’ll talk about the <a href="https://gdpr.eu/">General Data Protection Regulation (<strong>GDPR</strong>)</a> that<strong> applies to the EU</strong>, through the perspective of a data scientist who wants to build a model to predict whether or not an employee will quit his job in the following year. As it is just a matter of time that regulation increases within each region (we don’t know when…), this article will be kept as general as possible in order to broaden the scope outside of Europe, focusing on the main aspects and ideas of data regulation.</p><p><strong>Disclaimer:</strong> <em>it is relevant to highlight that </em><strong><em>this is not legal advice</em></strong><em>. You should always depend on the counsel of a Data Protection Officer (DPO) before taking any big step. This is </em><strong><em>not a plan of action</em></strong><em> but </em><strong><em>a summary of key considerations and useful suggestions</em></strong><em>. Also note that the specifics on the regulation discussed in this article may have changed at the moment you are reading it.</em></p><h3>Understanding the risks of non-compliance</h3><p>Even though our job as data scientists mainly consist of working with data and offering strategic points of view, we should always think about the consequences of what we are doing and if we are even allowed to proceed with a development under certain circumstances where ethics, morals and regulation intertwine. In a scenario where no one is raising any concern we would be the last person in line obliged to do so.</p><p>In this regard, GDPR compliance isn’t a mere suggestion, it’s a compulsory requirement. <a href="https://commission.europa.eu/law/law-topic/data-protection/reform/rules-business-and-organisations/enforcement-and-sanctions/sanctions/what-if-my-companyorganisation-fails-comply-data-protection-rules_en#:~:text=likely%20infringement%20%E2%80%93%20a%20warning%20may,business&#39;s%20total%20annual%20worldwide%20turnover.">GDPR infringement</a> carries significant risks for your company:</p><ul><li>A temporary or definitive ban on processing;</li><li>A fine of up to €20 million or 4% of the business’s total annual worldwide turnover;</li><li>Reputational damage in the form of the loss of customer and employee trust;</li><li>Financial battles caused by lawsuits from employees and customers whose data has been mishandled.</li></ul><p>Note that this does not exactly apply to regulation in other regions but as we know, every time a law appears, it sets a precedent for future legislation to develop in other places. In any case, this should serve as a trigger to question yourself if you are doing things the right way or at least to think whether or not it might be a good idea to start your developments without reading what comes ahead.</p><p>So, the consequences seem serious enough, right? Let’s go over some of the key considerations regarding regulation that should lower the anxiety caused by the previous bullet points.</p><h3>Key Considerations for GDPR Compliance</h3><p>First of all, from a data protection perspective, for all of those hearing about this for the first time, it is important to highlight that there is only one scenario where we should question whether or not to embark on a machine learning project: we are expected to build a model using <strong>personal data</strong> from users (for example customers or employees).</p><p>Here, we need to pay close attention to two broad aspects: data collection/usage, and data privacy preservation.</p><h4>A) Data collection and usage</h4><p>How much we’ll have to do about this point will vary depending on the solution we need to build. For example, maybe you are building an app and you still haven’t collected any user data. Or maybe you are a corporation that has been collecting data from users/customers/employees for a long time but the initial agreement between both parties limits your capacity of working with their data so you would have to make a new agreement.</p><p>Now let’s start with our example where we are using employee data (of course almost the same applies to customer data). Here are the key considerations we would need to keep in mind:</p><ul><li><strong>Data minimisation and purpose limitation:</strong> We need to ensure that the data collected is used only for the purpose it was collected, which should be explicitly defined prior to any data collection takes place as per the next point;</li><li><strong>Explicit consent:</strong> before any data collection process, you must obtain explicit consent from the individuals whose data will be processed. It’s essential to clearly inform the employees/users about the data you’ll be collecting, the purpose of the collection, and who will have access to it. This is generally covered during the employee/user onboarding process where an agreement is made to use certain platforms that the company provides such as resource management tools like Workday, SAP or any other HR platform (or in the case of customers/users the main app that will be collecting their data such as a transactional app in the case of a Fintech company). In the case of customers this should be stated in the terms of service agreement and data protection clauses;</li><li><strong>Privacy by design and default:</strong> Ensure that privacy settings are set at their highest level by default. Also, the entire data system should be designed to respect privacy rights from the start. In the case of employee data, this point is covered through the use of HR platform service providers only if you are not extracting data from these platforms (in that case further considerations are mentioned in section B). In the case of retail applications, further steps should be taken;</li><li><strong>Data subject rights:</strong> Ensure your systems/platforms can accommodate the rights of data subjects under regulations. These include the right to access, rectify, erase, restrict processing, data portability, object to processing, and oppose automated decision-making or profiling.</li><li><a href="https://gdpr.eu/data-protection-impact-assessment-template/"><strong>Data Protection Impact Assessment (DPIA)</strong></a><strong>:</strong> In cases where data processing is likely to put the individuals’ rights at a high risk GDPR demands a DPIA. This involves systematically considering the potential impact that a project or initiative might have on the privacy of individuals.</li></ul><p>In any case, as mentioned at the beginning of the article it would also be smart to appoint a DPO if your organisation carries out large scale data processing. They will help to monitor internal compliance, inform and advise on your data protection obligations, provide advice regarding DPIAs, and act as a contact point for data subjects and the supervisory authority.</p><p>So we are data scientists, should we worry about these points when trying to work with employee data? Well, note that most of these are covered the moment an employee joins an organisation and their data is introduced to an HR platform such as Workday or SAP HR modules. So the main concerns a data scientist should have are related to the preservation of data privacy. However, if we were to create an app for internal use that collects data from a new source we’ve created, we should go back and check we are complying with all the previous points.</p><h4>B) Data privacy preservation</h4><p>Suppose you’ve already complied with all the requirements of section A), and now is the time to start building a model to solve the employee attrition problem (here’s an introductory <a href="https://towardsdatascience.com/cracking-the-employee-attrition-problem-with-machine-learning-6ee751ec4aae">article</a> to the problem). As we know, in order to build a model we first need to extract/read data from some source. The problem here is that for us to be able to train a model to predict the voluntary resignation of employees we’ll need to be able to use their characteristics as predictive features (while excluding unethical variables such as gender, religion, sexual orientation, etc.). But these characteristics are composed of both personal data and metadata (i.e. data generated through the use of a platform that has users: can be footprints of behaviour such as logins, interactions and the description of these actions).</p><p>The main problem, or at least the only one directly stated, appears when handling sensitive <a href="https://commission.europa.eu/law/law-topic/data-protection/reform/what-personal-data_en#:~:text=Personal%20data%20is%20any%20information,person%2C%20also%20constitute%20personal%20data.">personal data</a>.</p><p>According to GDPR, personal data is:</p><blockquote>any information that relates to an identified or identifiable living individual. Different pieces of information, which collected together can lead to the identification of a particular person, also constitute personal data.</blockquote><p>Regulation expects that any process that will exploit the data should guarantee secure data processing. This means we need to pay attention to how we are extracting the data and how we are processing it. For example, if we were to extract personal data to a local instance of a computer, and this extraction is not transformed in a way that removes the possibility of identifying individuals, we would be infringing the regulation in two ways:</p><ul><li>Data is not securely stored;</li><li>Users/employees/customers are identifiable.</li></ul><p>So how do we deal with this? The first point is easy to solve, at least in general terms: we could work on secure cloud environments (in a supported region) where the data is safely protected from data breaches and only a selected group of authenticated users could access it.</p><p>Regarding the second point, some extra work should be done in order to de-identify the data <strong>upon extraction</strong>. However we must be careful about how we do this as it is stated that:</p><blockquote>Personal data that has been de-identified, encrypted or <strong>pseudonymised </strong>but can be used to re-identify a person remains personal data and falls within the scope of the GDPR.</blockquote><blockquote>Personal data that has been rendered <strong>anonymous</strong> in such a way that the individual is not or no longer identifiable is no longer considered personal data. For data to be truly anonymised, the anonymisation must be irreversible.</blockquote><p>The first paragraph showcases one of the main mistakes professionals make while trying to anonymise data i.e. they remove sensitive data such as names, surnames, addresses, phone numbers and emails, and hash the employee data to ids. The problem with this is that people may still be identifiable. How? Well, let’s look at the following simulated example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zbdJm0BxIvlHA558yccskA.png" /><figcaption>Image by Author</figcaption></figure><p>In this example we assume we have a database with employee’s information. Note that in the original data we can easily identify each individual. But what happens, when we just remove “sensitive data”? Well, as you can see we still have several ways to identify each individual. For instance:</p><ul><li>The worker_id tells us the order at which the players entered the club;</li><li>Just by looking at the age_group we can tell that one of the groups has a single member;</li><li>If we checked the nationality the same problem arises, we have several classes with a single observation;</li><li>Also even in the cases where the nationality is shared (english players), note that if we’d analysed their nationalities together with their age groups, 3 unique combinations can be created with them, allowing us to easily identify the individuals;</li><li>Lastly, the job position in this example has only two classes, where one class belongs to a single observation.</li></ul><p>What can we do to comply with the data privacy preservation requirement while processing the data? Let’s look at the following transformations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*InQAxUKKqoAwF0rMD-_Ilw.png" /><figcaption>Image by Author</figcaption></figure><p>The changes made are simple yet they required a little bit of thought. In short:</p><ul><li>Direct identifiers are removed as in the previous example;</li><li>The worker_id is hashed in case it had a meaning such as the relative onboarding to the company;</li><li>The age_group variable has been altered to remove the possibility of identifying the players within the age_group of 25–35 years;</li><li>The observation of the coach was removed (one alternative to keep it would be to generate a broader age_group and remove the job position);</li><li>The nationality was replaced for a boolean variable that signals if the player’s nationality matches the country of work. With this we avoid single classes and using a particular nationality to predict an outcome (may not be ethical under some strict optic).</li></ul><p>After all this changes this would be our working dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5FKcPImv5kiwWzKV8_RANQ.png" /><figcaption>Image by Author</figcaption></figure><p>Note that every minor change we make to the original data will also have consequences on the predictive quality of the features, as aggregation or observation removal may reduce the capability of detecting more precise patterns, so there’s a trade-off here (one we can try to minimise but not avoid). For instance, the fact that we are using the variable age_group with a subjective grouping instead of simply using the age, means we are already losing information, as the age groups that come from a business/platform definition are not necessarily helpful to explain particular behaviour. Maybe age groups of 22–25 years and 31–36 are better for prediction purposes. Nevertheless, in the anonymisation solution we are going a step further and subjectively aggregating already aggregated groups, so you can imagine that we are moving farther away from the optimum.</p><p>With the point being made, there are a few common approaches for correct data processing. Again, they may reduce the predictive power of a model in different proportions but that’s the price we have to pay. These are the following:</p><ul><li><strong>Pseudonymisation:</strong> This technique replaces private identifiers in a data set with artificial identifiers, or pseudonyms. It can help maintain privacy as the data cannot be attributed to a specific data subject without additional information. This would be the case of replacing the worker id for a hash (and storing their mapping in a secure location), or doing the same for any other field such as the company name (provided the database has several companies);</li><li><strong>Anonymisation:</strong> In contrast to pseudonymisation, anonymisation aims to remove or modify the identifying information so that it can’t be linked back to an individual, even with the additional information. This would be achieved in the second example we provided, where it is impossible to identify an individual after excluding fields, observations, and aggregating the data.</li><li><strong>Differential Privacy and Statistical Disclosure Control (SDC):</strong> This approach adds statistical noise to the data in a way that maintains the overall accuracy of the data while making it impossible to identify a single record. For example, if we had compensation data we could apply some function so that all the data is transformed by the same standard, making the final output lose it’s interpretability. However, it is important to highlight that, in most cases that use personal data models must be transparent, so you’d have to revert the transformation in order to be able to interpret the decision making process of the model and validate its conclusions.</li><li><strong>Data Masking:</strong> This involves obscuring specific data within a database to protect it. It can be static (where a copy of the data is masked) or dynamic (where data requests are masked in real time). This is a more general method that applies to what we’ve mentioned regarding hashing values to mask them.</li><li><strong>Federated Learning:</strong> This technique allows you to build machine learning models without directly accessing raw data. The data remains in its original location, and only model updates are shared, enhancing privacy. Although safe, this method implies that an already fixed model or packaged solution should be applied to the data which should be clean for the model to work. The problem is that if you’ve spent some time working with HR or customer data you’ll come to understand that there is not such thing as an industrialised way to process this data with and algorithm and make predictions. Why? Because data is not as clean as we believe/expect it to be, so we need to do some analysis on its quality before offering a plug and play solution to a customer. We don’t want to be seen as conmen, and more important than that, the model will have some impact on another living being so we are obliged to take every measure at our disposal to make sure the model is working as expected.</li><li><strong>Privacy-preserving Record Linkage (PPRL): </strong>This technique is used when you need to integrate data from different sources but don’t want to share identifiable data. PPRL methods ensure that only the linked (and not identifiable) data are shared. This is a really important point, as we may not have all the data we need in a single platform so we’d need to be capable of matching all their identifier in a way that data can be connected without sharing identifiable data.</li><li><strong>Homomorphic Encryption:</strong> This form of encryption allows computation on encrypted data, providing results as if the data was not encrypted. This method is beneficial when using cloud-based machine learning services, as the service provider doesn’t need to see the raw data. Regarding this point, more work still needs to be made in order for this to apply to more elaborate machine learning models. But it is still good to know that the option exists and continues to be developed.</li></ul><p>All in all, ensuring privacy should always be a priority when working with data. This list is not exhaustive, and the techniques used depend on the specific context and requirements of the project. Therefore, it’s essential to stay informed about the latest privacy-preserving techniques and always consider privacy from the outset of a project.</p><h3>Concluding remarks</h3><p>Building predictive models to understand employee and customer behaviour is undoubtedly a promising application of data science that could significantly empower an organisation and bring benefits to it’s stakeholders. However, as a wise man once said, “with great power comes great responsibility”, so it’s essential to remember that working with personal data is a serious matter. Regulation compliance should not be an afterthought but a core component of the project’s design and execution. With the correct approach and adherence to GDPR principles, we can take a framework that would allow us to unlock valuable insights while respecting and safeguarding individual privacy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8735373977c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[14 Requirements to Make your Machine Learning Project a Success (Part II)]]></title>
            <link>https://medium.com/data-science/14-requirements-to-make-your-machine-learning-project-a-success-part-ii-5a89600a7a16?source=rss-2939b50adecd------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a89600a7a16</guid>
            <category><![CDATA[business]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[tips-and-tricks]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[project-management]]></category>
            <dc:creator><![CDATA[Ezequiel Ortiz Recalde]]></dc:creator>
            <pubDate>Fri, 30 Dec 2022 08:54:52 GMT</pubDate>
            <atom:updated>2023-06-01T07:19:25.258Z</atom:updated>
            <content:encoded><![CDATA[<h4>Set yourself up for success and avoid a disaster</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FpSC7lG65AYLgKaPMCX5zw.png" /><figcaption>Photo by <a href="https://unsplash.com/@andrewtneel?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Andrew Neel</a> at <a href="https://unsplash.com/es/s/fotos/roadmap?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Sometimes we forget that developing and implementing machine learning models to solve real problems is… “hard,” to say the least. It’s not a surprise then that the success of a project that involves it does not happen by chance. Some may even say that there’s no way to guarantee it, but I can assure you that we can always take some measures to increase our odds of succeeding.</p><p>In this regard, throughout <a href="https://towardsdatascience.com/14-requirements-to-make-your-machine-learning-project-a-success-part-i-80c288be503d">part I</a> of this article we presented the most relevant management and development requirements that need to be addressed while approaching a machine learning project in order to avoid an undesirable outcome. For this purpose, 2 sets of requirements were provided together with a detailed explanation of the first one. Now is time to go over the second set. As a quick reminder, here are the requirements that, <strong>when not satisfied</strong>, could significantly reduce the likelihood of your project succeeding:</p><h4>Management requirements</h4><ol><li>Define the problem, the resources needed to solve it and possible limitations</li><li>Find key actors who have field knowledge of the problem at hand</li><li>Define the project scope</li><li>Define success metrics (both technical and business oriented)</li><li>Set soft/flexible deadlines</li><li>Give a global picture of how the development will be carried out</li><li>Find internal champions that will promote your project</li></ol><h4>Development requirements</h4><ol><li>Understand the data, its sources and generation process</li><li>Humble yourself up and research new solutions/algorithms</li><li>Don’t implement models you are not capable of explaining</li><li>Build benchmark models, fail fast and as many times as possible</li><li>Discuss your decisions with the whole team as frequently as possible while paying attention to your audience and prioritising transparency</li><li>Go through the development, testing and production stages</li><li>Document the whole process (not just the code)</li></ol><p>Let’s go over the development requirements.</p><h3>Development requirements in depth</h3><p>We’ve already talked about the requirements related to management decisions and actions that will boost your chances of delivering a successful project, but don’t forget that without some technical order you are still walking on thin ice.</p><p>Now we have a new question to answer:<strong> </strong>is there any bullet proof way of approaching a machine learning development from a technical perspective? Not really, but at least we can point out some of the basic values you should try to imprint into your work methodology: <strong>order </strong>(validated small steps, timing and documentation generation), <strong>accountability</strong> (task ownership and senior responsibility for failing to meet requirements) and <strong>transparency</strong> (honest, clear and frequent communication). How do we make sure we are doing it? Fulfilling the following set of requirements would be a good starting point.</p><h4><strong>1. Understand the data, its sources and generation process</strong></h4><p>You should never build a model before having a complete understanding of the data you are using. Here are some questions that should help you to get ready to start the development:</p><ul><li>Does the data come from a transactional system? a scraper? a form/survey? an ERP system?</li><li>What’s the frequency at which we generate/update the information?</li><li>Is this information being used for other purposes? If that’s the case, for which?</li><li>Are we following any data governance structure?</li><li>Can we use the data as it is or do we need to encrypt it due to privacy requirements?</li><li>Are these data sources stable or there’s some degree of uncertainty about their sustainability in the future?</li></ul><p>Once you’ve gone through these questions you will be prepared to assess whether or not you need to summarise all data sources (internal and external), document the existing variables, generate a data model (entity relationship diagram) and create a data contract that will ensure your database won’t be altered or deleted in the future. If you are starting in a scenario where the data is there but there is no documentation or agreements about its usage, you’ll have to buckle up, announce that there is no formal data model to everyone involved in the project, and put yourself to work on all points made at the beginning of this paragraph. And, don’t forget to change your deadlines…</p><p>Of course, you could ignore everything and proceed to start building the model. Though common, this is not advisable as you could end up making more mistakes than necessary because of an incorrect interpretation of the data, or even worse, finding that your model can’t be executed due to the fact that your databases have disappeared for some justified or unjustified reason (the point is, you did nothing to prevent this from happening).</p><h4><strong>2. Humble yourself up and research new solutions/algorithms</strong></h4><p>It does not matter whether you have 1, 5, 10 or +15 years of experience working in machine learning, you should always start a project by doing some research on the current solutions and latest academic publications. There may be more efficient, precise and less costly solutions available. Plus, with how fast the technological advancements are moving, the novel methods that you’ve learnt during your bachelor, masters or even the previous year, could be completely outdated by the time you are reading this article. Don’t get me wrong, they would still work but none of us should be ok with providing a subpar solution to an internal/external client.</p><p>As an advice I would recommend you to always do a brief summary of the relevant literature and current code implementations as the first task of the development stage (this will come in handy for requirements 3 and 7). Don’t forget that the end objective should always be to add more value at a lower cost (more complexity may not be the answer).</p><p>Finally, as a friendly warning, keep in mind that even senior data scientists fail to meet this requirement so a quick reminder is certainly important.</p><h4><strong>3. Don’t implement models you are not capable of explaining</strong></h4><p>This seems obvious yet with the surge of AutoML and the rapid emergence of new models, the scenario has been set for people to run models without understanding what they are doing.</p><p>For example, the treatment of missing values is one of the most critical steps in terms of the potential biases that it can cause in the model results. In some cases it would be completely wrong to fill the values due to a particular reason that explains why we have missing values in the first place (missing not at random). Nevertheless, there are models that claim that they can deal with them. Note: the fact that a model handles missing values by using some automatic imputation method does not mean that it is correct… it just means that the code will run and you’ll get a result.</p><p>On another note, we could be unknowingly using a combination of variables that could generate a potential target leakage problem in some models that are not prepared to deal with it given their architecture. The point is that not all models can work correctly with the same input and again, <strong>the fact that the code runs does not mean you are doing things right</strong>.</p><p>Finally, even if the paper that backs a model says that it does something you should always check that the implementation you are using is doing exactly what it is supposed to (in the times of open-source you may be surprised to find that sometimes it doesn’t).</p><h4><strong>4. Build benchmark models, fail fast and as many times as possible</strong></h4><p>Paradoxically, the key to success is swift failure. Don’t spend too much time building the best model possible before presenting initial results. You can always make another iteration to improve a benchmark model.</p><p>As hinted in <a href="https://towardsdatascience.com/14-requirements-to-make-your-machine-learning-project-a-success-part-i-80c288be503d">part I</a>, time and monetary resources are not infinite so you are better off failing fast and as many times as possible. This will allow your organisation/client to:</p><ul><li>Identify a benchmark model to be improved later on</li><li>Accelerate the project pace</li><li>Cut on expenditure</li><li>Get a more precise idea of what is achievable with the available data</li><li>Stop further developments of an unpromising project</li><li>Try more alternatives before taking a final decision</li><li>Obtain a more polished development in less time</li></ul><h4><strong>5. Discuss your decisions with the whole team as frequently as possible while paying attention to your audience and prioritising transparency</strong></h4><p>Communication skills will take you far. One of the worst mistakes you could make is not asking for a second opinion about your design decisions (to both technical and non-technical professionals). You may think you understand everything, and maybe you do, but it is almost impossible to stay sharp all the time. So, ask many questions, even the dumb ones could end up being not dumb at all.</p><p>Take advantage of the knowledge of the people that live with the problem you are trying to solve, they will help you find the exceptions and critical details that could take your project down the abyss. Besides avoiding simple mistakes, you will be involving the potential users of your solution. This will make knowledge transfer sessions progress seamlessly and facilitate the adoption of the new tools being developed. Plus, by prioritising transparency you’ll increase the trust in your work.</p><p>Here it is important to pay attention to your audience so that your message is structured in a way that it can be understood. Also, a good advice would be to do this frequently (at least once a week) so that you don’t allow mistakes or misunderstandings to pile up.</p><p>In addition, remember that this also applies to your code. Having your code reviewed by your teammates will help you improve your skills while detecting potential bugs and improvement opportunities.</p><h4><strong>6. Go through the development, testing and production stages</strong></h4><p>Development stages exist for a reason: order and risk mitigation. As mentioned in <a href="https://towardsdatascience.com/14-requirements-to-make-your-machine-learning-project-a-success-part-i-80c288be503d">part I</a>, the second worst model is the one that is not used. If you’ve spent resources on the development of a model you would expect it to be used by the business (one of the most fulfilling aspects of the job), and for that to happen you first need to be sure that it is ready for that, i.e. the model has been sufficiently tested together with the pipeline that generates de input data and makes the results available for end users.</p><p>Despite this being quite obvious, the truth is that many projects remain in unaccessible notebooks that are not prepared to be used by non-technical users, and in some cases not even technical users. Formalising the code into scripts ready to be included in a pipeline can be bothersome and boring, yet you should consider it compulsory. As a quick tip, I would advise to approach the development in an organised way by:</p><ul><li>Keeping your imports and functions commented and explained in specific “utils.py” scripts to be imported into you experimental notebooks</li><li>Taking advantage of the one main benefits of using notebooks: markdown and cell ordering. Use markdown to add sections (introduction and objective, data extraction, data processing, missing values imputation, feature engineering, etc.) with figures and exhaustive explanations of what you are doing. Finally, if you are like myself you may often find that you could have ordered some transformations/steps in a more efficient or less redundant manner, here is where conscious cell ordering comes in handy (but, <strong>don’t forget to check that you’ve made the changes necessary so that the code will work as expected after the rearrangements</strong>).</li><li>Generating the requirements file (I prefer to use yaml due to its clarity) with the packages and versions required to run the code in the notebook under fixed conditions</li><li>Discussing the structure of the results needed with the end users</li></ul><p>If you’ve followed these steps the process of moving the development to production should be much easier.</p><p>Lastly, <strong>if a certain iteration of the project does not include the deployment of the model in production you should be clear about it</strong>, as managing expectations is essential to avoid misunderstandings.</p><h4><strong>7. Document the whole process (not just the code)</strong></h4><p>Often neglected, documentation is the most valuable result of a development. Why? Documentation serves the same purpose as history books, to help us avoid past mistakes, understand our decisions and leave lessons to those that will come after us.</p><p>If you do not want to spend too much time writing a formal document of the project, a good alternative would be to use Jira or other project management tool. However, I still believe that besides using such tools, a formal document that mimics a paper with the following elements, though not compulsory, is always nice to have:</p><ul><li>A list of the people involved in the development</li><li>An abstract explaining the objective</li><li>An introduction about the project, its scope, its members and its steps</li><li>A summary of current relevant methods and implementations</li><li>An analysis of the variables and data model to be used</li><li>The details of the ETL (why did we take some decisions instead of others? whose idea was it?)</li><li>The model (why are we using model A instead of model B? how does it work?)</li><li>The results</li><li>The conclusions and possible extensions</li></ul><p>Note that if you followed the roadmap shown in <a href="https://towardsdatascience.com/14-requirements-to-make-your-machine-learning-project-a-success-part-i-80c288be503d">part I</a> you already have everything you need to sit down and write this report. It may be tiresome, I know, but if the developers exit the company without leaving any documentation, you won’t be able to provide a solution in a short amount of time whenever any problem or doubt arises. Well, even without them leaving the organisation we still have a problem, as we tend to forget about details or decisions we took a month ago (being optimistic here) so documentation is essential, you get the idea.</p><h3>Concluding remarks</h3><p>Throughout <a href="https://towardsdatascience.com/14-requirements-to-make-your-machine-learning-project-a-success-part-i-80c288be503d">part I</a> and II of this article we went over 14 of the most critical requirements to be taken into consideration in order to avoid a disaster while approaching a machine learning project. Given the multitasking nature of our profession, both management and development requirements were made with the objective of providing a richer and more global perspective (a frequently ignored one).</p><p>Hopefully this will help to bring some light on the complexity of these kinds of projects and add to the discussion about machine learning project management and development standards.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a89600a7a16" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/14-requirements-to-make-your-machine-learning-project-a-success-part-ii-5a89600a7a16">14 Requirements to Make your Machine Learning Project a Success (Part II)</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[14 Requirements to Make your Machine Learning Project a Success (Part I)]]></title>
            <link>https://medium.com/data-science/14-requirements-to-make-your-machine-learning-project-a-success-part-i-80c288be503d?source=rss-2939b50adecd------2</link>
            <guid isPermaLink="false">https://medium.com/p/80c288be503d</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[tips-and-tricks]]></category>
            <category><![CDATA[project-management]]></category>
            <category><![CDATA[business]]></category>
            <dc:creator><![CDATA[Ezequiel Ortiz Recalde]]></dc:creator>
            <pubDate>Wed, 21 Dec 2022 06:36:12 GMT</pubDate>
            <atom:updated>2023-06-01T07:20:36.790Z</atom:updated>
            <content:encoded><![CDATA[<h4>Set yourself up for success and avoid a disaster</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cb5gwPRJliy-3Eyw6EAyVw.png" /><figcaption>Photo by <a href="https://unsplash.com/@andrewtneel?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Andrew Neel</a> at <a href="https://unsplash.com/es/s/fotos/roadmap?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>A lot is being written about algorithms and novel solutions, yet not enough is spoken about how to carry out the development of a machine learning project that will add value to your organisation/company. Most of the times a project fails not because of the implementation of the “wrong” algorithm, but due to the lack of organisational support, a clear roadmap and a work methodology that is both straightforward and transparent. Even though this becomes much more critical in start-ups with tight budgets, the complexity of the problem increases in larger organisations where more actors need to be linked.</p><p>In this sense, whether you are creating a company from scratch with a product/service based on machine learning, or working in a start-up or a large company with little to no experience in these kind of projects, the objective of this article (divided into two parts) is to offer you a clear picture of how they should be handled to avoid wasting resources, which would in turn also help you to identify poorly organised teams and low quality machine learning external service suppliers that will doom your projects.</p><p>Then, what’s the recommended approach for machine learning? For some reason we love lists of top 10 steps/rules but in this case you’ll have to settle with 14. The following list is built based on my personal experience as a Data Scientist and Strategic Consultant, and the valuable stuff I’ve learnt from really insightful leaders. You can see it as a list of requirements that, <strong>when not satisfied</strong>, are likely to cause your project to fail sooner or later. For the sake of simplicity, the list is divided into 2 sets of requirements, those related to management decisions and those that involve technical reasons that are tightly linked to the development process:</p><h4><strong>Management requirements</strong></h4><ol><li>Define the problem, the resources needed to solve it and possible limitations</li><li>Find key actors who have field knowledge of the problem at hand</li><li>Define the project scope</li><li>Define success metrics (both technical and business oriented)</li><li>Set soft/flexible deadlines</li><li>Give a global picture of how the development will be carried out (a general example that will fit most of the cases is provided further ahead)</li><li>Find internal champions that will promote your project</li></ol><h4>Development requirements</h4><ol><li>Understand the data, its sources and generation process</li><li>Humble yourself up and research new solutions/algorithms</li><li>Don’t implement models you are not capable of explaining</li><li>Build benchmark models, fail fast and as many times as possible</li><li>Discuss your decisions with the whole team as frequently as possible while paying attention to your audience and prioritising transparency</li><li>Go through the development, testing and production stages</li><li>Document the whole process (not just the code)</li></ol><p>In part I we’ll go over the management requirements.</p><h3>Management requirements in depth</h3><p>It does not matter if your role does not involve management, for a project to succeed everyone needs to contribute to its order, even when this is not expected from you. In particular, this becomes much more important when working in technical developments that entail many complex tasks that cannot be carried out masterfully by a single person in a reasonable amount of time. In this regard, the last scenario you want to be in is one where someone without much technical knowledge makes promises that involve accomplishing the impossible, or even worse, reaching the end of the project and realising you made pretty serious mistakes that invalidate the whole development. With this in mind, let’s go over some of the most essential requirements you should try to meet while working on a development that involves machine learning.</p><h4><strong>1. Define the problem, the resources needed to solve it and possible limitations</strong></h4><p>Believe it or not, many projects start due to someone saying: <em>Let’s do some machine learning, it sounds cool and will help us in our road of digital transformation</em>. Some may even go even further and say: <em>I don’t care what we do but we need to innovate, AI will make us different from our competitors</em>. Besides these fictional examples, the point here is that machine learning should never be implemented just for the sake of saying you are using it or because it seems innovative. Sounds fair right?</p><p>In any case, the first step should always be to start by defining the problem you are trying to solve, the resources needed to do it and the possible limitations (I dare say that you may not even need to use machine learning). Some questions that need to be answered before starting would be:</p><ul><li>What are we trying to solve? Is it relevant? How will this benefit us?</li><li>Has this problem been solved before in other companies/industries?</li><li>How long could a potential development take?</li><li>Do we have enough data to do it? How do we extract it?</li><li>Do we have the infrastructure required to start a development?</li><li>Do we have the team required to go through with this project? If not, how do we build it?</li><li>What is our target/objective?</li><li>Which variables could be used?</li><li>Are there any legal restrictions (for example, GDPR or CCPA)? How would this change our answers to the previous questions?</li></ul><p>It is important to note that this requirement should be fulfilled in parallel with requirement number 2, as key actors both with several points of view and a relevant voice in the organisation are needed to answer most of the previous questions.</p><h4><strong>2. Find key actors who have field knowledge of the problem at hand</strong></h4><p>Even if you are an expert on the particular field that you are working in, you should always try to identify and involve a set of professionals that will aid you in the understanding of the whole problem, its intricacies and relevant details, from different perspectives. No one knows the problem/business better than the people who live with it. By keeping this in mind you will avoid taking obviously wrong approaches, while building on consensus.</p><p>Moreover, remember that even if you’ve solved the problem before or you’ve found a solution developed by a third party, it may not be the same problem once you take into consideration the semantic of the variables that belong to each company/organisation/database. In this sense, two companies can have the exact same database due to the fact that they share the same Finance/HR platform, but the meaning and relevance of each variable can be completely different based on how these platforms are used.</p><h4><strong>3. Define the project scope</strong></h4><p>Machine learning projects can take as much time as your creativity lasts. For example, if you ever worked in an ETL process, you should know that you could spend ages trying new imputation methods for missing values (if applicable), working on the detection of outliers/inconsistencies, testing new features/variables, and even looking for new data/external sources.</p><p>The question is where do you stop? Surely you can’t keep going on forever as you are expected to show results at some point in time… and the longer you take the longer you’ll have to wait to see some returns on your investment. The answer is to define a project scope that aims to build a minimum viable product (MVP) in a short span of time, and then build on top of it in future iterations of the project. Note: you should be clear and concise about what is included in this MVP so that no doubt can arise by the end of the project.</p><p>But what is an acceptable result and how long should you spend trying to achieve it? To answer this we have requirements 4 and 5 (arguably the most challenging ones).</p><h4><strong>4. Define performance metrics (both technical and business oriented)</strong></h4><p>Let’s address the two most important aspects of performance metrics: meaning and acceptable values.</p><p><strong>Meaning: </strong>If your most relevant internal stakeholders cannot explain in simple terms how you measure the performance of your model then you are doing things wrong, as this shows a complete lack of scoping, transparency and consideration for the business needs. In this sense, you should take your time to discuss and explain how you are going to measure the performance. For example, we know that for classification problems, accuracy may be a poor metric, or even misleading when classes are heavily imbalanced. In this example, precision, recall or the f1-score could be some of the better alternatives that can be chosen based on the business objective. Another example would be the time series demand forecasting of products for inventory management, where badly specified models aim to minimise single value loss functions (RMSE, MAE, MAPE, SMAPE, etc.) instead of using a Quantile Loss function that could provide the business with time-varying stock-level policies. If needed, do not be afraid of building custom loss functions.</p><p><strong>Acceptable values: </strong>you may be tempted to propose acceptable values based on your past experience but, as we know, that is not a wise decision as the quality (consistency and variability) and volume of the available data will tell what is reasonable/achievable. Don’t be that person. First try a simple version of the model you are going to use and check the results, that should be enough to allow you to propose an acceptable value.</p><h4><strong>5. Set soft/flexible deadlines</strong></h4><p>Answering how long it will take to finish a project will never be easy (unless the project is really simple). Again, even if you solved the problem before, you might find yourself against several common problems such as:</p><ul><li>bad quality data</li><li>the lack of a data model (or the presence of a messed up one)</li><li>poor variable and process documentation</li><li>slow IT departments that take a lot of time to give you access to the resources you need to work (cloud services for example)</li><li>little to no support from the key actors you’ve identified and so on</li></ul><p>To cope with the first three, the best thing you can do is to ask for a couple of days (less than a week) to swiftly go over the data related problems. Once you’ve managed to get a glimpse of the current status of the data you can then propose some soft/flexible deadlines that should vary no more than 2 weeks during the MVP phase. If you are not able to make the first assessment because you are an external consultant/service provider, then you can still provide an answer… Let’s be honest, if you have a capable team of 2/3 data scientists, for most common modelling problems no development of an MVP should take more than 3 months (provided that data engineering tasks are not needed and you are not expected to build a platform). You may be wondering, but what is a common modelling problem? Here are some business oriented examples:</p><ul><li>Demand time series forecasting</li><li>Customer/competitor segmentation</li><li>Recommendation systems</li><li>Text classification</li><li>Sentiment and topic analysis (the simplest and fastest to implement)</li><li>Survival analysis models (customer/employee churn/attrition)</li><li>Price elasticity of demand (done right, not with a simple regression and theoretical distributions)</li><li>Supply chain optimisation (maybe the only one that could take more time to solve but only if it is the first time you are working on it)</li></ul><p>Regarding problems that are similar to the last two i.e. delays that involve the proactivity of others, be clear about the expected response times and how its non-compliance will play in the development time.</p><h4>6. Give a global picture of how the development will be carried out</h4><p>For the majority of the cases, your projects should follow the same global structure as the one described in the following figures:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wa77_yg_cO1F8krA81e3ig.png" /><figcaption>Image by Author</figcaption></figure><p>You should always aim to first build a prototype by following some standard steps that should be supported by the completion of the previous requirements:</p><ul><li>Defining the problem and scope</li><li>Identifying and extracting the relevant data</li><li>Implementing filters (if applicable), analysing missing data and outliers</li><li>Working on the feature engineering process</li><li>Defining the modelling approach, i.e. under what theoretical framework are we going to be working</li><li>Build a benchmark model and improve it</li><li>Check the performance of the model</li><li>Repeat the whole process until the prototype is good enough according to requirement 4</li></ul><p>By showing this workflow you are adding to the transparency of your work and giving a hint about the complexity of the problem to non-data professionals involved in the process. This will in turn help you explain in a clearer manner the possible delays that may occur (specially in the data processing steps).</p><p>Once the prototyping stage is cleared, the frequently neglected step that involves moving the final model to production should be addressed. A brief depiction of this process is shown in the next figure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*waABbdlvFkF_a3oFRhjjMg.png" /><figcaption>Image by Author</figcaption></figure><p>In short, you need to define the architecture of the solution (nowadays mostly cloud components), organise your code into executable scripts that run on dedicated environments, build a pipeline and orchestrate its execution, build a monitoring process to keep track of the changes in the model performance (beware of data drift), formalise the documentation and, if possible, explore new extensions and identify improvement opportunities.</p><h4><strong>7. Find internal champions that will promote your project</strong></h4><p>This last requirement applies only in large organisations. You’ll quickly see why.</p><p>The second worst model is the one that is not used. You may have done a terrific job while developing through consensus and using the latest state-of-art algorithms but, if the users don’t see the value of your work you still have one last task to do i.e. make them use it willingly. Here’s where change management strategies come into play, as most of the times the usage of new tools requires some cultural adaptations within the organisation (the larger the worse). The good news is that if you followed the first two requirements i.e. the definition of the problem was discussed and supported by key actors, half of the job is done as there would be additional enforcement coming from the top management. In any case, it is always useful to find internal champions that will promote your projects and enforce their usage within their teams, other teams or even areas of the organisation (maybe you developed a solution that was only intended to be used by a specific area but with some slight changes it could be of help to others).</p><h3><strong>Concluding remarks</strong></h3><p>All in all, we’ve gone through some of the most critical requirements that you should consider while approaching a new machine learning project. Many of them may sound obvious to some, but as we know, everything management-related sounds obvious once you read it. At the minimum, this article should either work as: <strong>a)</strong> a quick reminder of mistakes to avoid for fellow professionals; <strong>b)</strong> a standard to demand from external/in-house data teams.</p><p>As a final advice, always aim/demand for transparency, consensus and quality (if possible don’t rush things). I hope you find value in this short read and stay close for <a href="https://towardsdatascience.com/14-requirements-to-make-your-machine-learning-project-a-success-part-ii-5a89600a7a16">part II</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80c288be503d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/14-requirements-to-make-your-machine-learning-project-a-success-part-i-80c288be503d">14 Requirements to Make your Machine Learning Project a Success (Part I)</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[An Introduction to Organizational Network Analysis]]></title>
            <link>https://medium.com/data-science/an-introduction-to-organizational-network-analysis-cfa91a0e2fda?source=rss-2939b50adecd------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfa91a0e2fda</guid>
            <category><![CDATA[insights-and-data]]></category>
            <category><![CDATA[human-resources]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[business]]></category>
            <dc:creator><![CDATA[Ezequiel Ortiz Recalde]]></dc:creator>
            <pubDate>Wed, 29 Jun 2022 12:55:29 GMT</pubDate>
            <atom:updated>2023-06-01T07:20:11.368Z</atom:updated>
            <content:encoded><![CDATA[<h4>Use graph theory to improve employee engagement and communication through influencers and key actors detection</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GKP7skEPHipru7n8taNkSA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@adrienconverse?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Adrien Converse</a> on <a href="https://unsplash.com/es/s/fotos/brain?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>During the past months I’ve been researching data science solutions designed to help the area of human resources in their daily tasks. Why? Well, let’s say it is a really interesting area that, in my opinion, doesn’t get enough attention. Regardless of the organization, the future success of a company relies heavily on their current and future employees, so why not focus on them? In this regard, I’ve found that most of the standard solutions revolve around the following ideas:</p><ul><li>CV Parsers;</li><li>Chatbots for recruiting;</li><li>Employee churn models;</li><li>Recommender systems for training courses.</li></ul><p>As you can see, except for the churn models, these solutions fail to provide strategic value for a company and real benefits for employees. But, what can be done then? Well, another relevant set of solutions that is not really talked too much about belongs to the topic of <em>Organizational Network Analysis</em>. In this introduction we will go through the key concepts behind it with some simulated examples in Python to make things easier to digest. So, what is <em>Organizational Network Analysis</em>? To be able to answer this question we first need to understand the concept of organization network.</p><h4>A) Networks: a tool to understand your organization</h4><p>As mentioned by Barabási (2013), the organization network is a social network formed by the members of an organization that regularly interact with each other. According to Tichy, N., Fombrun, C. (1979), this network is characterised for representing social interactions in terms of social objects (people or groups) where not necessarily every object is connected to the whole network due to the lack of interactions, and some of them can share more than one connection. Furthermore, through these interactions the actors of the network establish links by sharing information, affection, influence and goods or services. In other words, we have a network of employees (nodes) that are linked through their interaction (edges). This functional representation of an organization can be helpful to understand several work dynamics that otherwise would be hidden.</p><p>From this perspective, Liu, J., Moskvina A., Ouředník, M. (2017) formally define<em> Organizational Network Analysis</em> (ONA) as the systematic exploration of the organizational networks through the use of techniques taken from graph theory. Its objective is to gain a better understanding of the management structures, the interpersonal relationships and the flow of information inside an organization. In this regard, the scope of this analysis can be really broad: from descriptive analytics of the characteristics of detected influencers, informal leaders, people that resign (exit the network), and highly/poorly engaged employees, to predictive models that aim to provide real value through a more robust interpretation of these kinds of internal behaviours. However, keep in mind that as in any data science project, the data maturity of the organization needs to be considered before offering any of these solutions (you should start by gathering and processing the data with a well defined objective, then offer analytics, and finally move on to predictive and prescriptive models).</p><p>Now you may be thinking that all of this sounds good, but in order to make any type of analysis you first need to get a hold of the organization network, which can be quite tricky. To do so, one can follow the main approach which consists of making surveys where all employees are asked to nominate other co-workers (of any area of the organization) as referents of different aspects of their work life. These surveys could be done online or through any of the popular resource management tools such as <em>Workday. </em>Some of the questions asked could be:</p><ul><li>Who are the people you seek when you want to know important information about the future of the company? (there’s a nice and detailed example of this in Barabási’s Network Science book).</li><li>Who are the people that give you emotional support?</li><li>Who are the people that you rely on when you need to solve technical tasks (for example, using software A)?</li><li>Who is the person that motivates you the most?</li><li>Who are the people you regularly interact the most during your day?</li></ul><p>As you can see, the success of the correct representation of the network depends on the participation rate and the honest response of employees that know that their answers aren’t anonymous. Here, it is key for the Human Resources department to take an active role in the whole process (as a suggestion, they could make the surveys compulsory and work on communicating their benefits — mentioned later — to achieve better results).</p><p>After finishing the data collection step, we can build the directed graph (network) where the nodes are employees and their directed links represent a nomination from one to another. As an example from a simulation I will explain later on, for an organization with 40 members this would look as something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8i5sEim0PKDbQxxO55z5Gg.png" /><figcaption>Image by author</figcaption></figure><p>In this graph, the colours represent some grouping attribute of the nodes that helps us classify them (in this case, it refers to the area where each employee was assigned to “work” in). Note that the arrows point to the direction of the nominations, and in the cases where no nominations were received or emitted we have isolated nodes.</p><p>Once we finished building the network, it is time to look for the influencers and key actors of the organization. But, what exactly is an influencer or key actor? How can we tell? This isn’t set in stone as there are several ways in which someone can fall in either of these categories, and they are a “little bit” more complex than just considering the most nominated people. For example, if we take into consideration the set of questions listed above, there are at least 4 types of influential people. Some of them might be key to the information flow of the organization, while others may be essential motivators, emotional supports or technical referents. Additionally, we can find members that help other people reach these influential people (which in turn also makes them influential). Nevertheless, at the minimum we can say that all of them share a quality: some degree or type of centrality inside the network. Here’s where we need to introduce some individual metrics taken from network science that are imperative for this kind of analysis. For the sake of keeping things simple we will just mention the main ideas behind some of them:</p><ul><li><strong><em>Degree</em>: </strong>The degree of a node is defined as the number of links from other nodes that point to this. When the network is directed it is necessary to make a distinction between the links that point to a node (in-degree) and the links that point from a node to other nodes (out-degree). Following the example of this article, you can think of it as the number of people that nominated you vs the number of people you nominated.</li><li><strong><em>Closeness centrality</em></strong>: this metric (between 0 and 1) measures the average distance of a node to the rest of the nodes in the network (in terms of the number of steps needed to reach them). This allows us to have a notion of the average proximity to the rest of the network. Through this perspective, you could identify an influencer or key actor as the person (or people) whose <em>closeness index</em> is above certain threshold.</li><li><strong><em>Betweenness centrality</em></strong>: this metric (between 0 and 1) can be seen as a way to quantify the influence that a node has on the information flow of the network. It is mainly used to find nodes that serve as a bridge between groups of nodes. It is computed by calculating the shortest path between all the pairs of nodes, which allows to measure the frequency at which a node is located between the shortest paths of other nodes.</li><li><strong><em>Hubs and authorities scores</em>:</strong> these scores (between 0 and 1) help us classify the nodes into three types: regular, hubs and authorities. Their characterisation can be summarised as follows: some nodes (hubs) have many links pointing to a few others (authorities) that aren’t frequently linked to the rest of the nodes (regular). One of the most common examples of this behaviour occurs in paper citations where the main knowledge is concentrated in the foundational papers (authorities), that in turn are cited by a series of papers (hubs) that are more frequently cited by the rest of the papers (regular). In the case of an organization network, authorities could be seen as leaders that communicate mainly with hubs who work as bridges between authorities and “regular” employees. Hence, we could say that both, hubs and authorities can be seen as key actors within the professional network.</li></ul><p>If we were to calculate these metrics for a network such as the one above, we would obtain a table similar to this one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rBXFzjka-9ZtLITWlnVXgg.png" /><figcaption>Image by author</figcaption></figure><p>Next, all that is left is to decide on some rules and thresholds to define what kind of behaviour we’ll be considering as indicative of being an influencer. An oversimplified approach could be to go with the top 5 scores of each of the six metrics and for each of them define a different class of actor. For example, those with the highest <em>DegreeIn</em> could be called “Sought members”, the top employees with <em>DegreeOut</em> could be named “Proactive members”, those with the highest <em>Closeness</em> and <em>Betweenness</em> scores could be called “Central members” and “Connector members” respectively, and finally we have the “Hubs” and “Authorities” of the network. Note that these are some random names I just thought about, you are free to choose the names you’d like.</p><p>By this point, besides the detected influencers, we also have an approximation to the “informal” organization with a set of network statistics per employee, and that by itself is quite valuable. The question is then, what can you do with this information? As mentioned in the title of this article, you could try to improve employee engagement and communication. How? Well, I’m neither a sociologist nor psychologist so I recurred to published papers and informal talks with professionals that work in the field to provide you the following list of summarised ideas:</p><ul><li>You can improve the information flow by spreading messages through the key detected nodes, which can aid with the perceived transparency of the organization and therefore improve employee engagement;</li><li>You could improve the onboarding of new employees by pairing them with some of the key nodes;</li><li>Processes of change management that require the selection of change leaders could take advantage of the ones detected with this approach. Likewise, it can be useful in cases where there’s a need to track the variation in the interactions of the members before and after the implementation of a new tool;</li><li>During merger and acquisition processes, the whole methodology could be adapted to find knowledge experts and leaders that could aid to reduce the burden of such a stressful process, while keeping the operations running as smooth as possible;</li><li>Paying attention to isolated or rarely nominated nodes may be a good idea, as being poorly connected to the organization may be indicative of a bad work life experience, low job satisfaction and engagement (Kahn, W. A. , 1990), and a deficient communication system. If you combine all this elements you could be in front of a member that is more prone to resign;</li><li>Finally, and more interestingly, you could go beyond the descriptive statistics of <em>Organizational Network Analysis (</em>not ML or AI<em>) </em>and start thinking about implementing predictive models that try to answer some common questions using the additional information provided by the network as features. For example, given enough time you could complement your churn models with the network data obtained through several surveys.</li></ul><p>Before concluding the general introduction to the topic of <em>Organizational Network Analysis</em>, it is important to highlight that this approach is not strictly constrained to the professional organization, since it could also be adapted to an educational institution (for both the staff and alumni) or any other context where a network of people can be created.</p><p>Next, for those interested in the “behind the scenes”, I describe how to build a basic network through a simulated scenario that assumes you were able to carry out a survey that simply asks you to nominate the members of the organization with whom you interact the most.</p><h4>B) Simulating a network</h4><p>We start by importing the libraries we’ll be using:</p><pre># General<br>import itertools as it<br>import numpy as np<br>import pandas as pd</pre><pre># Network<br>import networkx as nx</pre><p>Before proceeding with the creation of the network, we first need to think about what design parameters we’ll be using. As the purpose is to create a fictional organization where different kinds of “influential” people can be found, we will need to specify:</p><ul><li>The number of employees;</li><li>The number and names of the areas where the employees will be assigned;</li><li>The size of the areas to know how many employees will “work” in each of them;</li><li>The proportion of people that can have a higher probability of nominating/being nominated by others in each area;</li><li>The probability of nominating/being nominated of highly connected people;</li><li>The maximum probability of nominating/being nominated of the employees that do not belong to the highly connected class;</li><li>The probability that a member of Area A nominates someone of Area B, as some areas are more likely to interact than others.</li></ul><p>Given that, we now specify the global parameters that will define the network:</p><pre># GLOBAL PARAMETERS<br># Set a seed to replicate the experiment<br>np.random.seed(1)</pre><pre># Specify the number of employees in the network<br>n_employees = 40</pre><pre># Specify the areas<br>m_areas = [&#39;HR&#39;, &#39;IT&#39;, &#39;Finance&#39;, &#39;Marketing&#39;, &#39;Sales&#39;]</pre><pre># Specify the area sizes as percentage of total<br>area_sizes = [0.5/5, 2/5, 1/5, 0.5/5, 1/5]</pre><pre># Set the percentage of highly connected people per area<br>influencer_ratio=0.1</pre><pre># Give a higher probability of connection to a type of employee<br>influencer_link_probability=0.85</pre><pre># Give an upper bound to the link probability of a non &quot;influencer&quot; employee<br>max_non_influencer_link_probability=0.6</pre><pre># Create all pairs of areas to define their interaction probability<br>areas_links_combinations = list(it.combinations(m_areas,2))</pre><pre># Specify the probability of each pair<br>areas_links_probability = [0.1, 0.2, 0.3, 0.4,<br>                           0.4, 0.2, 0.7, 0.7,<br>                           0.6, 0.9]</pre><p>Next, we create the employees and we assign them to an area:</p><pre># Generate a list of employees<br>employees = [f&#39;Employee_{n}&#39; for n in range(n_employees)]</pre><pre># Generate an array of employee&#39;s areas<br># using the area sizes as assignment probabilities</pre><pre>employees_areas=np.random.choice(a=m_areas,<br>                                 size=n_employees,<br>                                 replace=True,<br>                                 p=area_sizes)</pre><pre># Join the data into a pandas DataFrame<br>df=pd.DataFrame({&#39;Employee&#39;:employees,&#39;Area&#39;:employees_areas})</pre><p>Once we have our DataFrame of employees and areas we define the nomination probability of each of them:</p><pre># For low link probability people a random uniform distribution<br># is used</pre><pre>lower_proba_assignment=lambda x : np.random.uniform(<br>non_influencer_link_probabilities[0],<br>non_influencer_link_probabilities[1])</pre><pre># Assign the link probabilities per area and combine the data<br>dfs=[]<br>for area in m_areas:</pre><pre>  df_area=df[df[&#39;Area&#39;]==area].copy()</pre><pre>  area_employees = df_area.shape[0]</pre><pre>  n_influential = round(area_employees*influencer_ratio)</pre><pre>  influ_employees=df_area[&#39;Employee&#39;].sample(n_influential).values</pre><pre>  df_area[&#39;Link_Probability&#39;]=np.where(<br>                          df_area[&#39;Employee&#39;].isin(influ_employees),<br>                          influencer_link_probability,<br>                          df_area[&#39;Employee&#39;].apply(<br>                                            lower_proba_assignment))<br>  dfs.append(df_area)</pre><pre>df=pd.concat(dfs,ignore_index=True)</pre><p>Our DataFrame looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*nfkuHvIfxsNA3OJXL5MElw.png" /><figcaption>Image by author</figcaption></figure><p>Now that we have the nodes and the individual probability to nominate/be nominated, we can proceed to create their links. To do so, we’ll start by generating all possible combinations of links (excluding the cases where they nominate themselves).</p><pre># Create the links DataFrame<br>possible_links=list(it.product(df[&#39;Employee&#39;],df[&#39;Employee&#39;]))<br>df_links=pd.DataFrame(possible_links, columns=[&#39;From&#39;,&#39;To&#39;])<br>df_links=df_links[df_links[&#39;From&#39;]!=df_links[&#39;To&#39;]].copy()</pre><p>After obtaining all the pairs we have the following data structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/236/1*qRNhvFL71Tlv-AQp03uCig.png" /><figcaption>Image by author</figcaption></figure><p>What we need to do now is to define which links we are going to be keeping based on the area each employee belongs to (some areas are more likely to interact), and their assigned nomination probability (some people are more prone to being nominated/nominate than others). To do that we need to merge the DataFrame with employees and link probabilities with the links DataFrame:</p><pre># Merge links DataFrame with employee data based on the &#39;From&#39; side<br>df_links=pd.merge(df_links,<br>                  df[[&#39;Employee&#39;,&#39;Area&#39;,&#39;Link_Probability&#39;]],<br>                  left_on=&#39;From&#39;,<br>                  right_on=&#39;Employee&#39;,<br>                  how=&#39;left&#39;)</pre><pre># Drop the employee column as we&#39;ll need to do another merge<br>df_links.drop([&#39;Employee&#39;],axis=1, inplace=True)</pre><pre># Rename columns to know to what employee the data belongs to<br>df_links.rename(columns={&#39;Area&#39;:&#39;From_Area&#39;,<br>                        &#39;Link_Probability&#39;:&#39;From_Link_Probability&#39;},<br>                        inplace=True)</pre><pre># Merge links DataFrame with employee data based on the &#39;To&#39; side<br>df_links=pd.merge(df_links,<br>                  df[[&#39;Employee&#39;,&#39;Area&#39;,&#39;Link_Probability&#39;]],<br>                  left_on=&#39;To&#39;,<br>                  right_on=&#39;Employee&#39;,<br>                  how=&#39;left&#39;)</pre><pre># Rename the columns<br>df_links.rename(columns={&#39;Area&#39;:&#39;To_Area&#39;,<br>                         &#39;Link_Probability&#39;:&#39;To_Link_Probability&#39;},<br>                          inplace=True)</pre><pre># Drop the employee column as we don&#39;t need it anymore<br>df_links.drop([&#39;Employee&#39;],axis=1, inplace=True)</pre><pre>df_links.rename(columns={&#39;Area&#39;:&#39;To_Area&#39;,<br>                         &#39;Link_Probability&#39;:&#39;To_Link_Probability&#39;},<br>                         inplace=True)</pre><p>With the previous step we joined the individual link probability, but we still need to add the probability of nominations between members of different areas. In particular, as there are two ways of showing a pair of areas (A,B) and (B,A), we’ll need to mirror the probabilities of linkage:</p><pre># Start by creating a DataFrame with the first way<br>external_proba_a=pd.DataFrame(areas_links_combinations,<br>                              columns=[&#39;From_Area&#39;,&#39;To_Area&#39;])</pre><pre>external_proba_a[&#39;Area_Pair_Probability&#39;]=areas_links_probability</pre><pre># Mirror the previous transformation but renaming the columns<br>external_proba_b=external_proba_a.copy()</pre><pre>external_proba_b.rename(columns={&#39;From_Area&#39;:&#39;To_Area&#39;,<br>                                 &#39;To_Area&#39;:&#39;From_Area&#39;},<br>                                 inplace=True)</pre><pre># Concatenate both DataFrames<br>external_proba=pd.concat([external_proba_a,<br>                          external_proba_b],<br>                         ignore_index=True)</pre><pre># Link the DataFrame of links with the &quot;external&quot; probabilities<br>df_links=pd.merge(df_links,<br>                  external_proba,<br>                  on=[&#39;From_Area&#39;,&#39;To_Area&#39;],<br>                  how=&#39;left&#39;)</pre><pre># In the cases where the area is the same<br># we&#39;ll keep a probability close to 1 (0.9)<br># meaning the nomination depends mainly on the individual<br># probability</pre><pre>df_links[&#39;Area_Pair_Probability&#39;]=np.where(<br>  df_links[&#39;From_Area&#39;]==df_links[&#39;To_Area&#39;],<br>  0.9, df_links[&#39;Area_Pair_Probability&#39;])</pre><pre># For the majority of the cases, the final pair probability<br># will equal the average between individual probabilities<br># times the area probability</pre><pre>df_links[&#39;Pair_Probability&#39;]=df_links[&#39;Area_Pair_Probability&#39;]*  (df_links[&#39;From_Link_Probability&#39;]+<br> df_links[&#39;To_Link_Probability&#39;])/2</pre><pre># In case an employee has the highest link probability<br># we&#39;ll make him more prone to receive nominations than to make<br># nominations by halving the pair probability </pre><pre>df_links[&#39;Pair_Probability&#39;]=np.where(<br>df_links[&#39;From_Link_Probability&#39;]==influencer_link_probability,<br>df_links[&#39;To_Link_Probability&#39;],df_links[&#39;Pair_Probability&#39;]/2)</pre><pre>df_links[&#39;Pair_Probability&#39;]=np.where(<br>df_links[&#39;To_Link_Probability&#39;]==influencer_link_probability, df_links[&#39;From_Link_Probability&#39;],<br>df_links[&#39;Pair_Probability&#39;]/2)</pre><pre><br># Finally, use the Pair_Probability to flip a coin<br># and decide if the pair will be considered (Active_Link=1) or not</pre><pre>df_links[&#39;Active_Link&#39;]=df_links.apply(lambda x: np.random.binomial(n=1,p=x[&#39;Pair_Probability&#39;]),axis=1)</pre><p>Thanks to this step, we are able to define our nodes and links:</p><pre>nodes = employees</pre><pre># We create a list of tuples of pairs of nodes to define the links<br>links = df_links[df_links[&#39;Active_Link&#39;]==1][<br>                 [&#39;From&#39;,&#39;To&#39;]].to_records(index=False)</pre><p>Now we are ready to build the network and calculate the metrics:</p><pre># Create an instance of a Directed Graph using networkx<br>G = nx.DiGraph()</pre><pre># Add the nodes and links to the graph<br>G.add_nodes_from(nodes)<br>G.add_edges_from(links)</pre><pre># Calculate all the metrics mentioned in the previous section:</pre><pre># DegreeOut<br>degree_df_out=pd.DataFrame(G.out_degree,<br>                           columns=[“Employee”,”DegreeOut”])</pre><pre># DegreeIn<br>degree_df_in=pd.DataFrame(G.in_degree,<br>                          columns=[“Employee”,”DegreeIn”])</pre><pre># Closeness<br>closeness_df=pd.DataFrame.from_dict(nx.closeness_centrality(G),<br>                                    orient=”index”).reset_index()</pre><pre>closeness_df.columns=[“Employee”,”Closeness”]</pre><pre># Betweenness<br>betweenness_df=pd.DataFrame.from_dict(nx.betweenness_centrality(G),orient=”index”).reset_index()</pre><pre>betweenness_df.columns=[“Employee”,”Betweenness”]</pre><pre># Hubs and Authorities<br>hubs, authorities = nx.hits(G, normalized=True)</pre><pre>hubs_df=pd.DataFrame.from_dict(hubs, orient=&quot;index&quot;).reset_index()<br>hubs_df.columns=[&quot;Employee&quot;,&quot;HubScore&quot;]</pre><pre>authorities_df=pd.DataFrame.from_dict(authorities,<br>                                      orient=&quot;index&quot;).reset_index()</pre><pre>authorities_df.columns=[&quot;Employee&quot;,&quot;AuthorityScore&quot;]</pre><pre># Merge the results<br>results=pd.merge(df, degree_df_in, on=&quot;Employee&quot;,how=&#39;left&#39;)<br>results=pd.merge(results, degree_df_out, on=&quot;Employee&quot;,how=&#39;left&#39;)<br>results=pd.merge(results, closeness_df, on=&quot;Employee&quot;,how=&#39;left&#39;)<br>results=pd.merge(results, betweenness_df, on=&quot;Employee&quot;,how=&#39;left&#39;)<br>results=pd.merge(results, hubs_df, on=&quot;Employee&quot;,how=&#39;left&#39;)<br>results=pd.merge(results, authorities_df, on=&quot;Employee&quot;,how=&#39;left&#39;)</pre><pre>results=results.sort_values(by=&#39;Closeness&#39;, ascending=False)</pre><p>With this last step, a table such as the one showed in the first section of the article is obtained. As you can see, it is fairly simple to adapt the code to use real data (you would only need to run the last chunk after defining the nodes and links from the nominations).</p><h4>Concluding Remarks</h4><p>Throughout this article we’ve discussed the main ideas behind <em>Organizational Network Analysis</em>,<em> </em>while proposing some use cases and providing the tools necessary to begin a simple project in your organization/institution. In this sense, I encourage you to try to run your own simulated scenarios and if possible, take the next step towards the development of predictive models based on network metrics. From my experience, these metrics do add valuable information to predictive models (at least to those of churn and engagement).</p><h4>References</h4><p>Tichy, N., Fombrun, C. 1979. Network analysis in organizational settings. <em>Human Relations</em>, 32(11), 923–965.</p><p>Barabási, A. L. 2013. Network science. <em>Philosophical Transactions of the Royal Society A: Mathematical, Physical and Engineering Sciences</em>, 371(1987), 20120375.</p><p>Liu, J., Moskvina A., Ouředník, M. 2017. Towards a decision support system for organizational network analysis using multiplex interpersonal relations. <em>Multi-agent and Complex Systems. Springer</em>, 33–47.</p><p>Kahn, W. A. 1990. Psychological conditions of personal engagement and disengagement at work. <em>Academy of management journal</em>, 33(4), 692–724.</p><p>Karanges, E., Johnston, K., Beatson, A., Lings, I. 2015. The influence of internal communication on employee engagement: A pilot study.<em> Public Relations Review</em>, 41.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfa91a0e2fda" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/an-introduction-to-organizational-network-analysis-cfa91a0e2fda">An Introduction to Organizational Network Analysis</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[Fleet and Workforce Planning with Linear Programming]]></title>
            <link>https://medium.com/data-science/fleet-and-workforce-planning-with-linear-programming-16db08c7f91d?source=rss-2939b50adecd------2</link>
            <guid isPermaLink="false">https://medium.com/p/16db08c7f91d</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[business]]></category>
            <category><![CDATA[editors-pick]]></category>
            <category><![CDATA[linear-programming]]></category>
            <dc:creator><![CDATA[Ezequiel Ortiz Recalde]]></dc:creator>
            <pubDate>Tue, 12 Apr 2022 10:32:12 GMT</pubDate>
            <atom:updated>2023-06-01T07:21:00.180Z</atom:updated>
            <content:encoded><![CDATA[<h4>A preview of Linear Programming’s capabilities to solve some business problems</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2kp0XCd6yhZt1VU1vLIDiQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@popnzebra?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Pop &amp; Zebra</a> on <a href="https://unsplash.com/s/photos/workers?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Businesses (should) spend a lot of time and effort trying to predict the demand of their products/services, or the effort/resources required to complete different tasks so as to maximise their returns while avoiding mainly two undesirable outcomes:</p><ul><li>Falling short of resources or workers to cope with the demand, which could result in either processes failing or sales and client losses;</li><li>Having way too many unused resources (overstocking) or unemployed workers, which means extra costs for storing goods and an opportunity cost in the case of the employees (maybe they could be assigned to other tasks).</li></ul><p>Supposing a company has already managed to develop an accurate predictive model of their products/services’ demand, then the next step could be to organise the logistics behind their products replenishment and its tasks’ allocation in anticipation of the future demand. For example, this could mean finding an answer to the following questions:</p><p><strong>i.</strong> From which warehouses is it cheaper to send the product “P” units that are expected to be sold within the next week/month, to each of my stores?</p><p><strong>ii.</strong> How can I achieve this while taking into consideration the number of units available at each warehouse?</p><p><strong>iii.</strong> What about the available transportation resources? How can I use my available vans/trucks to move the boxes of stock from warehouses to stores? What is the less costly option, considering that there’s a fixed limit of boxes that each van can transport?</p><p><strong>iv.</strong> How can I assign the available workforce to each van while considering that some of my workers fought during a chess tournament last week and might end up fighting again if they are assigned to the same vehicle?</p><p>The question is then, how can one answer these types of questions that seem quite specific and different in nature? Well, we’d need to have a framework that allows us to build a fully customisable solution from scratch, where we can specify our objective and the real world constraints that define what is a feasible outcome of this objective. How about writing real life problems as systems of equations?</p><p>In this article, we’ll be simulating these scenarios and presenting a straightforward solution to the 4 questions proposed using a mathematical modelling approach known as Linear Programming. Though not in the data science spotlight, this is a famous optimisation technique/framework used to solve systems of linear equations that consist of an objective function (what we want to maximise/minimise, e.g. maximise profit while minimising costs), and a set of linear constraints that specify the different conditions that we need to meet in order to reach a feasible solution.</p><p>Basically, we write the problem we want to solve in linear terms specifying the objective and constraints, and then use optimisation algorithms (solvers) to navigate through thousands or millions of feasible and infeasible outcomes in a smart and efficient way, allowing us to at least come close to an optimal solution. But, what do we mean by optimal? In this framework optimal means the best feasible configuration of parameters that make up the final solution. Note that due to this, “optimal” may refer to completely different things depending on the business’ preferences/rules. For example, for one company satisfying the demand of their customers may be more important than saving transportations costs, while that may not be the case for others. At the end, it all comes to the correct specification of the business objective and its constraints.</p><h3>A Problem, A Framework, A Solution</h3><p>To answer the previous questions we’ll start by introducing a fictional setting. The context will be kept simple as the main aim of the article is just to introduce the framework and the idea of how we can use it to solve real life problems by developing custom solutions. Before starting, I’d like to clarify that the images/equations/code blocks that will appear from here onwards are all from my personal elaboration. Ok, let’s go straight to the point.</p><h4>1. Context and sample results</h4><p>Suppose you own a company, with a catalogue of <strong>5 </strong>products (<em>P=5</em>), <strong>3 </strong>warehouses (<em>W=3</em>), 3 stores (<em>S=3</em>), <strong>4</strong> vans (<em>V=4</em>) to transport the products and <strong>8</strong> employees (<em>E=8</em>) that can be assigned to each van in pairs (we can think that one is the driver and the other one the assistant). As mentioned at the beginning you already have an estimate of the expected demand. Furthermore, we’ll assume that due to the fact that you’ve estimated the demand, you’ve also stored enough stock to meet it, thus knowing how much stock you have in each warehouse.</p><p>To simplify the problem, instead of considering units of products, we’ll talk about boxes of products i.e. the demand and stock of a product is measured in boxes of the product (in a real life scenario after predicting the demand of products that are delivered in boxes/packages we’d need to convert the raw number into the number of boxes or grouping units needed as that’s the way of transporting them).</p><p>Next, we’ll assume you also know how much it costs to move a box of each product from any of your warehouses to any of your stores using any of your vans. Besides this variable cost, there’s also a fixed cost for using each vehicle (you can think of it as a depreciation/maintenance cost).</p><p>Additionally, we’ll suppose that there’s a limit to the number of trips each van can make. In this case the limit is 5 trips. What’s more, each van has a default number of boxes that it can fit in. On top of that, each of these vehicles (if used) needs to have employees assigned in pairs (a driver and an assistant) in order to be operational. Also, we can only assign each employee to a single van, and if we do, he’ll receive a fixed salary of $1500.</p><p>Finally, during a chess tournament that occurred the previous week, some of the employees got into a brawl so it is desirable to avoid assigning a pair of conflicting workers to the same van; as a matter of fact, we have 23 pairs of conflicting employees (<em>J=23</em>). If we do end up assigning them to the same van, we’ll have to deal with the consequences i.e. a penalty of $500.</p><p>In summary our context variables are the following:</p><ul><li>“P” products = 5</li><li>“W” warehouses = 3</li><li>“S” stores = 3</li><li>“V” vans = 4</li><li>“E” employees = 8</li><li>“J” conflicting pairs of employees = 23</li></ul><p>And the assumptions are:</p><ul><li>We know the demand in boxes of each of our products, by store;</li><li>We know how many boxes of our products are available in each of our warehouses;</li><li>All the boxes have the same size (to simplify the problem);</li><li>We know how many boxes fit in each of the vehicles;</li><li>The cost of sending a box varies depending on the combination of product-warehouse-store-van;</li><li>The use of each van has a fixed cost;</li><li>The vans can’t go from a warehouse to a store without transporting at least 1 box;</li><li>The vans can’t do more than 5 trips. We can assume that they all occur on the same day;</li><li>There’s a limit to how many boxes can be transported by each van;</li><li>None of the vans can repeat the same trip;</li><li>We need 2 employees assigned per van to be able to make a trip;</li><li>If we assign an employee we have to pay him for this task 🙂;</li><li>Each employee can only be assigned to a single van;</li><li>It is desirable to avoid assigning conflicting employees to the same vehicle.</li></ul><p>Then, the problem we have to solve is finding the optimal (less costly) way of transporting product boxes from warehouses to stores employing different vans and workers while fulfilling the constraints of demand, stock, vans and workers assignment.</p><p>The results look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*LWyTsjaZ2cwJIOzaaBWULA.png" /></figure><p>This table illustrates the results obtained (final cost) in different scenarios with partial variations in some parameters (conflict penalty, van fixed costs and number of employees). Note that the possibility of experimenting with different parameters is one of the main strengths of this framework. Of course, the analysis would be richer if we tried several changes at once such as allowing the vans to make more trips while reducing the penalty costs and increasing the number of conflicts. In fact, I encourage you to try some of these changes later.</p><p>Ok, from now on things will get a little more technical…</p><h4>2. Variables, objective and constraints</h4><p>The first thing we need to establish are the variables that we are going to use in the system of equations that define the problem. Here’s a list of them, with their description and range of values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1TMLxc4gOJQZiUTsr1TpYw.png" /></figure><p>Now that we’ve specified the variables, we’ll write the problem. In mathematical terms, the problem to solve is the following:</p><p><strong><em>i) </em>The objective</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EQKIML9r402eimCnE3eWAA.png" /></figure><p>(1) This is the objective function represented as the sum of four terms: <em>a)</em> the sum of unit costs times the number of boxes of product <strong><em>p</em></strong> sent from warehouse <strong><em>w</em></strong> to store <strong><em>s</em></strong> using van <strong><em>v</em></strong>;<em> b)</em> the sum of fixed costs <strong><em>F</em></strong> of the vans used; <em>c)</em> the sum of the salaries of the employees <strong><em>e</em></strong> assigned to van <strong><em>v</em></strong>; <em>d)</em> the penalty cost for not complying with the optional constraint of not assigning the conflicting pair of employees <strong><em>j </em></strong>to the same van <strong><em>v</em></strong>.</p><p><strong><em>ii) </em>The constraints</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*oB3IsWFmDZQdZkivFBVtiA.png" /></figure><p>(2) The first restriction specifies that the demand of each product <strong><em>p</em></strong> at each store <strong><em>s</em></strong> must be satisfied, i.e. the sum of all the combinations of product boxes sent from each warehouse <strong><em>w</em></strong> to each store <strong><em>s</em></strong> using any of the vehicles <strong><em>v</em></strong> must equal the number of boxes needed by the store to cover their expected demand;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*dZmAXXyJGAnmNYGKbUvIZw.png" /></figure><p>(3) Stipulates that we can’t send boxes that we don’t have. In other words, the sum of product boxes sent from a warehouse must be lower or equal than its available boxes;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*wXm255Qvhv7cYXax32sU4Q.png" /></figure><p>(4) Specifies that we can’t surpass the limit of boxes that can fit the van, so the sum of boxes transported in each vehicle must be lower or equal to the van’s capacity (<strong><em>capacity_v)</em></strong> at each trip. With this constraint we count the number of trips a van will make with the auxiliary variable <strong>Z_wsv</strong>, as <strong><em>capacity_v</em></strong> is the maximum number of boxes that can be transported at each trip by vehicle <strong><em>v</em></strong>, we can count as one trip the transportation of several products. Also, this constraint implicitly blocks the possibility of repeating the same trip;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*enk-Am-T_IzRAz9iLzQdlA.png" /><figcaption>Image by Author</figcaption></figure><p>(5) Signals that none of the vans can make more than 5 trips while also checking if each of them was used or not. Note that this constraint is chained with the previous one. How? Well, once we know if a trip was made or not by using constraint (4), we simply sum the number of <strong><em>Z_wsv</em></strong> and require that the total is lower or equal than 5 (the trip limit). Here, due to the specification of the equation, <strong>T_v</strong> will be equal to 1 unless the van is left unused;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*N_vEICvpPuSX48yoPqqwGA.png" /><figcaption>Image by Author</figcaption></figure><p>(6) Specifies that each van will have 2 or zero employees assigned;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*Q9nyhZMwsQLIpb6f3ZoM6Q.png" /><figcaption>Image by Author</figcaption></figure><p>(7) Requires that each employee can only be assigned to a single van;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M777oUzzSRWdwyNZL_WyPA.png" /></figure><p>(8) This constraint accounts for the fact that the desirable constraint on the pair of conflicting employees <strong><em>j</em></strong> is optional. When a pair of conflicting employees <strong><em>j=</em></strong>(<strong><em>e1</em></strong>, <strong><em>e2</em></strong>) is assigned to the same van (<strong><em>A_ve1</em></strong> + <strong><em>A_ve2 </em></strong>= 2) then the penalty is activated (<strong><em>G_vj</em></strong>=1) so that the equation equals zero. If just one member of the pair is assigned to a van then <strong><em>H_vj</em></strong>=1. If none of the conflicting employees of pair <strong><em>j</em></strong> is assigned to the van <strong><em>v </em></strong>then all the elements are zero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*pSBnMtXyCGQipO--8Xe-lw.png" /></figure><p>(9) The final constraint specifies the upper and lower bound for each variable. Here we declare which variables are binary and which ones are integers.</p><p>The complete problem is then expressed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lp6vvydD3rZA5evpzhfxQQ.png" /></figure><p>Since we’ve already managed to write the problem, we can proceed to code the solution of these examples using <a href="https://developers.google.com/optimization"><strong>Google OR-Tools</strong></a> with Python. But, before proceeding it is important to highlight that taking your time to complete the previous step is quite relevant, as it will allow you to get a better grasp of the problem at hand, while potentially avoiding some future bugs in your code and helping you explain your reasoning to your fellow data science teammates.</p><h4>3. Solution</h4><p>You can check the whole solution in this <a href="https://github.com/eortizrecalde/linear_programming/blob/beb8662089f38b29fd22f993fce4ab4bcadaee88/planning_lp.ipynb">notebook</a>.</p><p>First, we import the packages we’ll be using for this example.</p><pre>import numpy as np<br>import pandas as pd<br>from ortools.linear_solver import pywraplp</pre><p>The solution consists of the following steps:</p><ol><li>Set a seed to be able to replicate the simulation;</li><li>Declare the number of warehouses, products, stores, vans, employees and trip limit;</li><li>Set some thresholds for the simulated data and values for the fixed salary and the penalty for assigning a pair of conflicting employees to the same van;</li><li>Generate the matrices of costs (1 per product), the stock vector (1 per product, showing its stock available at each warehouse), the demand vector (1 per product, showing its demand at each store), a list of capacity per van (how many boxes each of them can transport per trip) and finally, the list of pairs of conflicting employees;</li><li>Call an instance of a solver that can be used to find a solution to the type of problem at hand (Integer Programming or Mixed Integer Programming);</li><li>Create the variables;</li><li>Define the constraints;</li><li>Define the objective function and the problem (maximisation/minimisation);</li><li>Solve and verify that the results comply with the constraints.</li></ol><p>We start with steps 1–4. As we are simulating the problem, the costs and quantities are created with a random variable, but in a real scenario we’d need to use the inputs given by the business. The process looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e4aca2f4c09530c0f012108261a1853/href">https://medium.com/media/4e4aca2f4c09530c0f012108261a1853/href</a></iframe><p>Now, to complete step 5 we need to instantiate a solver. In this case, we are using <a href="https://developers.google.com/optimization/reference/python/linear_solver/pywraplp"><em>pywraplp</em></a> from <a href="https://developers.google.com/optimization"><strong>Google OR-Tools</strong></a>. Note that there are several solvers available in <em>pywraplp</em> such as <em>GLOP</em>, <em>SCIP</em>, <em>GUROBI</em> and <em>IBM CPLEX</em>. Since <em>GUROBI</em> and <em>CPLEX</em> require a licence and <em>GLOP</em> is designed for simple Linear Programming but the problem we have at hand requires a solver to approach Integer or Mixed Integer Linear problems, we’ll use <a href="https://www.scipopt.org/"><strong><em>SCIP</em></strong></a> (one of the fastest non-commercial solvers that can handle Integer and Mixed Integer Linear problems).</p><pre>solver = pywraplp.Solver.CreateSolver(&#39;SCIP&#39;)</pre><p>After that, we continue with step 6 i.e. the definition of the variables that make up the system of linear equations.</p><p>First, for each combination of product, warehouse, store and van, we need to create an <strong><em>x</em></strong> variable with indices <strong><em>p</em></strong>(product), <strong><em>w</em></strong>(warehouse), <strong><em>s</em></strong>(store), <strong><em>v</em></strong>(van) that tells us the integer number of boxes of product <strong><em>p</em></strong> sent from warehouse <strong><em>w</em></strong> to store <strong><em>s</em></strong> using van <strong><em>v</em></strong>. These integer variables (solver.IntVar) are restricted to positive numbers (<em>lower bound</em> = 0 and <em>upper bound</em> = <em>solver.infinity()</em>). Furthermore, to keep track of each specific variable and future constraints, we carefully name them. An example of one of these variables is <strong><em>x_1_1_1_1</em></strong>.</p><pre>x = {}<br>for p in range(P_products):<br>  for w in range(W_warehouses):<br>    for s in range(S_stores):<br>      for v in range(V_vans):<br>        x[p,w,s,v] = solver.IntVar(lb=0,<br>                                  ub=solver.infinity(),<br>                                  name=f&quot;x_{p+1}_{w+1}_{s+1}_{v+1}&quot;)</pre><p>Second, we generate the boolean variable (<em>solver.BoolVar</em>) <strong><em>T_v</em></strong> that tells us if van <strong><em>v</em></strong> is used, which is required to be able to assign a cost for its usage.</p><pre>T = {}<br>for v in range(V_vans):<br>  T[v] = solver.BoolVar(name=f&quot;T_{v+1}&quot;)</pre><p>Third, we create variable <strong><em>A_ve</em></strong>, which signals if employee <strong><em>e</em></strong> is assigned to van <strong><em>v</em></strong>. We need to do this in order to be able to consider the cost of the work of the employees.</p><pre>A = {}<br>for v in range(V_vans):<br>  for e in range(E_employees):<br>    A[v,e] = solver.BoolVar(name=f”A_{v+1}_{e+1}”)</pre><p>Fourth, we generate the variable <strong>Z_wsv</strong>, an auxiliary boolean variable used to count the number of trips a van makes. Each of them will tell us if the trip from warehouse <strong><em>w</em></strong> to store <strong><em>s</em></strong> was assigned to van <strong><em>v.</em></strong></p><pre>Z = {}<br>for v in range(V_vans):<br>  for w in range(W_warehouses):<br>    for s in range(S_stores):<br>      Z[w,s,v] = solver.BoolVar(name=f”Z_{w+1}_{s+1}_{v+1}”)</pre><p>Lastly, we generate variables <strong><em>H_vj</em></strong> and <strong><em>G_vj</em></strong>.<strong><em> H_vj </em></strong>signals that just 1 of the conflicting employees of the conflicting pair <strong><em>j</em></strong> was assigned to van <strong><em>v</em></strong>. Variable <strong><em>G_vj</em></strong> signals that both members of a pair of conflicting employees <strong><em>j</em></strong> were assigned to van <strong><em>v</em></strong>.</p><pre>H = {}<br>G = {}<br>for v in range(V_vans):<br>  for j in range(len(J_employees_conflicts)):<br>    H[v,j] = solver.BoolVar(name=f&quot;H_{v+1}_{j+1}&quot;)<br>    G[v,j] = solver.BoolVar(name=f&quot;G_{v+1}_{j+1}&quot;)</pre><p>After creating the variables, we proceed to generate the linear constraints (we use the method <em>solver.Add</em> to do this). Regarding the demand constraints, we declare that the sum (<em>solver.Sum</em>) of the stock sent from each warehouse must equal the store’s demand. In the case of the stock constraints, we specify that the sum of the stock sent to each store must be lower or equal to the available stock at each warehouse. In both cases we use the function <em>product</em> from the library <a href="https://docs.python.org/3/library/itertools.html"><strong>itertools</strong></a> to obtain the cartesian product of possible combinations (warehouses, vans) and (stores, vans).</p><pre><strong># Demand constraint<br></strong>for p in range(P_products):<br>  for s in range(S_stores):<br>    solver.Add(<br>    solver.Sum(<br>    [x[p, j[0], s, j[1]] for j in itertools.product(<br>                                  range(W_warehouses),<br>                                  range(V_vans))]) == demands[p][s],<br>                                  name=&#39;(2) Demand&#39;)</pre><pre><strong># Stock constraint<br></strong>for p in range(P_products):<br>  for w in range(W_warehouses):<br>    solver.Add(<br>    solver.Sum(<br>    [x[p, w, j[0],j[1]] for j in itertools.product(<br>                                   range(S_stores),<br>                                   range(V_vans))]) &lt;= stocks[p][w],<br>                                   name=&#39;(3) Stock&#39;)</pre><p>Note that we added a name to each restriction using the parameter “name”. This will allow us to identify them in the standard problem representation (LP format) using the function <em>solver.ExportModelAsLpFormat</em>, which I strongly advise you to use<em>:</em></p><pre>print(solver.ExportModelAsLpFormat(obfuscated=False))</pre><p>Here’s a snapshot of how the constraints look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KsyeN1QAJ4yYvETUHlgRtw.png" /></figure><p>This is a sample of the demand and stock constraints (remember that <strong><em>x</em></strong> takes the form <strong><em>x_pwsv</em></strong>). The first one, as requested, shows that the number of boxes of product <strong><em>p=5</em></strong> sent from any warehouse <strong><em>w</em></strong> to store<strong><em> s=3 </em></strong>using any van <strong><em>v </em></strong>must equal the <strong><em>demand=3 </em></strong>of store<em> </em>3<strong>, </strong>which was<strong> </strong>generated before using a random variable. The stock constraint shows that the number of boxes of product <strong><em>p=1</em></strong>, sent from warehouse <strong><em>w=1</em></strong> to any of the stores <strong><em>s</em></strong>, using any of the vans <strong><em>v</em></strong> must be lower or equal to <strong><em>stock=11</em></strong>, the randomly generated stock of product 1 for warehouse 1. The rest of these specific constraints follow the same logic.</p><p>Next, we add the trip and vans’ use constraints. With the first one we ask that none of the vans can transport more boxes than its capacity allows per trip, while also checking if a trip from warehouse <strong><em>w</em></strong> to store <strong><em>s</em></strong> was assigned to van <strong><em>v</em></strong>. The second constraint aids us to verify if van <strong><em>v</em></strong> was used.</p><pre><strong># Trip verification constraint</strong><br>for v in range(V_vans):<br>  for s in range(S_stores):<br>    for w in range(W_warehouses):<br>      solver.Add(<br>      solver.Sum(<br>      [x[p, w, s, v] for p in range(P_products)])<br>      &lt;= capacities[v]*Z[w, s, v],<br>      name=&#39;4) TripVerification&#39;)</pre><pre><strong># Van use and trip limit constraint<br></strong>for v in range(V_vans):<br>  solver.Add(<br>  solver.Sum(<br>  [Z[j[0], j[1],v] for j in itertools.product(<br>                            range(W_warehouses),<br>                            range(S_stores))]) &lt;= trip_limit*T[v],<br>                            name=&#39;5) TripLimit&#39;)</pre><p>Let’s see a sample of how these constraints look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mKFSBCSZxyJ3b0lCYX9E7w.png" /></figure><p>On one hand, constraint <em>TripVerification_63</em> checks if van <strong><em>v=4</em></strong> was assigned to go from warehouse <strong><em>w=3</em></strong> to store <strong><em>s=3</em></strong>. Note that the term <strong><em>Z_wsv</em></strong> is multiplied by 4, which is the capacity of van <strong><em>v</em></strong>. This means that to comply with the constraint, the highest sum of quantities transported can’t be greater than 4. Also, in any case, for all quantities higher than 0, <strong><em>Z_wsv</em></strong> must equal 1. And that’s how we verify if a trip was assigned to be done.</p><p>On the other hand, the example of the <em>TripLimit</em> constraint implies that the sum of all possible trip paths (<strong><em>w_s</em></strong>) of van <strong>v=1</strong>, must be lower or equal to 5 (the trip limit that we set at the beginning) as we have the term of <strong><em>-5T_1</em></strong>. Note that this last term will also tell us if van <strong>v=1</strong> will be used. The same logic is applied to the rest of the vans in the remaining constraints of this class.</p><p>After this, we follow up with the final constraints: <em>(6)</em> <em>EmployeeRequirement</em>,<em>(7)</em> <em>JobLimit</em> and <em>(8) ConflictVerification</em>. With <em>EmployeeRequirement </em>we ask that for a van to be used, it must have two employees assigned. Next, <em>JobLimit</em> implies that we can’t assign an employee to more than 1 van. And finally, <em>ConflictVerification</em> is built to verify whether or not each pair of the <strong><em>J</em></strong> employee conflicts is assigned to the same van.</p><pre><strong># Number of employees per van</strong><br>for v in range(V_vans):<br>  solver.Add(<br>  solver.Sum(<br>  [A[v,e] for e in range(E_employees)]) == 2*T[v],<br>  name=&#39;6) EmployeeRequirement&#39;)</pre><pre><strong># Number of vans an employee can be assigned to<br></strong>for e in range(E_employees):<br>  solver.Add(<br>  solver.Sum([A[v,e] for v in range(V_vans)]) &lt;=1,<br>  name=&#39;7) JobLimit&#39;)</pre><pre><strong># Verification of the constraint compliance<br></strong>for v in range(V_vans):<br>  for idx,j in enumerate(J_employees_conflicts):<br>    solver.Add(<br>    solver.Sum([A[v,j[0]-1]])==-A[v,j[1]-1]+H[v,idx]+2*G[v,idx],<br>    name=&#39;8) ConflictVerification&#39;)</pre><p>A sample of the first two would be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5U0b0YLqElQRQToQroC5Zw.png" /></figure><p>Both constraints are straightforward. <em>EmployeeRequirement_69</em> tells us that for van <strong>v=4</strong> to be used, we need to have at least 2 employees assigned to it. <em>JobLimit</em> specifies that employee <strong><em>e=1</em></strong> can be assigned to just 1 van.</p><p>Regarding the last constraint, probably the hardest one to understand, we have 2 examples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3i7DSerFR1bznM7Z_uf89A.png" /></figure><p><em>ConflictVerification_152 </em>checks<em> </em>if the conflicting pair of employees <strong><em>j=8</em></strong>, composed of employees <strong><em>e=2</em></strong> and <strong><em>e=3 </em></strong>is assigned to van <strong><em>v=4</em></strong>. If just 1 of these employees is assigned to it, then <strong><em>H_4_8</em></strong> must equal 1 for the equation to equal 0. If both employees are assigned to this van, then <strong><em>G_4_8 </em></strong>must equal 1 for the equation to equal 0. Note that only the second case would have an impact on the total cost as the penalty of $500 would be activated. In the case of ConflictVerification_152, we can directly see that it checks the exact same thing but for conflicting pair <strong><em>j=9</em></strong>, composed of employees <strong><em>e=2</em></strong> and <strong><em>e=4</em></strong>.</p><p>Since we’ve finished writing the series of constraints, we are ready to continue with step 8 i.e. the definition of the objective function and the type of problem (maximisation/minimisation). To do so, we first create a list to save each of the terms described before as the objective function is simply the sum of all of them. Then, after adding all the terms we specify that we want to solve a minimisation problem (<em>solver.Minimize</em>).</p><pre><strong># Objective Function<br></strong>objective_function = []</pre><pre><strong># First term -&gt; Transportation variable costs<br></strong>for p in range(P_products):<br>  for w in range(W_warehouses):<br>    for s in range(S_stores):<br>      for v in range(V_vans):<br>        objective_function.append(costs[p][w][s][v] * x[p, w, s, v])</pre><pre><strong># Second term -&gt; Transportation fixed costs<br></strong>for v in range(V_vans):<br>  objective_function.append(costs_v[v]*T[v])</pre><pre><strong># Third term -&gt; Salary payments<br></strong>for v in range(V_vans):<br>  for e in range(E_employees):<br>    objective_function.append(fixed_salary*A[v,e])</pre><pre><strong># Fourth term -&gt; Penalties for not avoiding conflicts<br></strong>for v in range(V_vans):<br>  for j in range(len(J_employees_conflicts)):<br>    objective_function.append(conflict_penalty*G[v,j])</pre><pre><strong># Type of problem<br></strong>solver.Minimize(solver.Sum(objective_function))</pre><p>Here’s the whole objective function, where all variables are binary except for <strong><em>x</em></strong>, that is an integer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6uT0E6NkYJlRKbAUoLKPTQ.png" /></figure><p>Finally we use the Solve method to run the optimisation algorithm.</p><pre># Call the solver method to find the optimal solution<br>status = solver.Solve()</pre><p>All that’s left is checking the solution. To do this we call the solution status, if it is optimal (<em>pywraplp.Solver.OPTIMAL</em>) we print the value of the objective function, if that’s not the case we should check our previous work and look for inconsistencies in the problem definition.</p><pre>if status == pywraplp.Solver.OPTIMAL:<br>  print(<br>   f&#39;\n Solution: \n Total cost = ${solver.Objective().Value()}&#39;<br>   )<br>else:<br>    print(<br>    &#39;A solution could not be found, check the problem specification&#39;<br>    )</pre><p>For this simulation, the solution is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*rhoIvcE7BW4zUSSGKJ49eQ.png" /></figure><p>This means that the optimal transportation of products from warehouses to stores using vans, ends up costing $22,499. Now we have to decide whether or not this is good enough. If we think we can find a better solution by modifying the definition of the problem, we should think of how we can add/remove or modify some of the constraints or, if possible, how to alter the context variables. If we believe this is ok, then the next natural step would be to check the optimal values of the variables of the model, as from a planning perspective, it is highly relevant to be able to tell which are the vans that are going to be used, who are the employees that are going to be working in these tasks; which of them are assigned to which van; which are the trips that need to be planned and the quantity and types of products transported at each of them.</p><p>For the sake of finishing this article, we’ll just assume that there’s nothing left to do so we can proceed to check the optimal values of the relevant variables by extracting the solution details.</p><h4>4. Fleet and workforce planning details</h4><p>To begin the extraction of useful details we follow a simple procedure: i) extract the optimal values for each variable; ii) preprocess and rearrange the data into a table; iii) query the table with different filters. Here’s i) and ii):</p><pre>result_list = []</pre><pre><strong># Extract the solution details and save them in a list of tables<br></strong>for var in [x,Z,T,A,H,G]:<br>  variable_optimal = []<br>    for i in var.values():<br>      variable_optimal.append(i.solution_value())<br>    <br>      var_result=list(zip(var.values(),variable_optimal))<br>    <br>      df=pd.DataFrame(var_result,columns=[&#39;Name&#39;,&#39;Value&#39;])<br>    <br>      result_list.append(df)</pre><pre><strong># Concatenate the tables and extract the variable names<br></strong>results=pd.concat(result_list)<br>results[&#39;Name&#39;]=results[&#39;Name&#39;].astype(str)<br>results.reset_index(drop=True,inplace=True)<br>results[&#39;Variable&#39;]=results[&#39;Name&#39;].str.extract(&quot;(^(.)\d?)&quot;)[0]<br>results[&#39;Variable&#39;]=results[&#39;Variable&#39;].str.upper()<br>results[&#39;Value&#39;]=results[&#39;Value&#39;].map(int)</pre><pre><strong># Create a mapping of variables and indices to simplify the analysis<br></strong>variable_indices={&#39;X&#39;:&#39;X_product_warehouse_store_van&#39;,<br>                  &#39;A&#39;:&#39;A_van_employee&#39;,<br>                  &#39;T&#39;:&#39;T_van&#39;,<br>                  &#39;H&#39;:&#39;H_van_pair&#39;,<br>                  &#39;G&#39;:&#39;G_van_pair&#39;,<br>                  &#39;Z&#39;:&#39;Z_warehouse_store_van&#39;}</pre><pre>results[&#39;Indices&#39;]=results[&#39;Variable&#39;].map(variable_indices)</pre><pre><strong># Order the columns<br></strong>results=results[[&#39;Variable&#39;,&#39;Indices&#39;,&#39;Name&#39;,&#39;Value&#39;]].copy()</pre><p>This would be a sample of the main table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*tfCgKE0BMvh3hSllUJRN-w.png" /></figure><p>Next, after creating our main dataframe, we look for the vans that we are going to use by filtering the column <em>Variable</em> with “T” (binary variable to signal the usage of the vehicle) and the column <em>Value </em>with 1 (which means, the optimal solution implies that we need to use these vans):</p><pre>list(results[(results[‘Variable’]==’T’)&amp;(results[‘Value’]==0)].Name)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*UbEwIpH-NdMzybs8syyYaQ.png" /></figure><p>The results show that vans 1, 2 and 3 will be used.</p><p>For the next part, we’ll just search for the variables related to van 1, starting with answering which trips are going to be made using this vehicle. Here it is important to remember that van <strong>v=1</strong> corresponds to the index <strong>v=0</strong>:</p><pre>trips_van_1=[]<br>for w in range(W_warehouses):<br>  for s in range(S_stores):<br>    for v in range(V_vans):<br>      if v==0:<br>        trips_van_1.append(str(Z[w,s,v]))</pre><pre>trips_df=results[(results[&#39;Variable&#39;]==&#39;Z&#39;)&amp;(results[&#39;Value&#39;]&gt;0)]</pre><pre>display(trips_df[trips_df[&#39;Name&#39;].isin(trips_van_1)])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*95xsHnV4uvr-Mksv_Evrmg.png" /></figure><p>We can see that van 1, is assigned the following 5 trips:</p><ul><li>Warehouse 1 to store 1 and 3;</li><li>Warehouse 2 to store 2;</li><li>Warehouse 3 to store 2 and 3;</li></ul><p>Next, we need to find the employees that are going to be in charge of the delivery operations of van 1:</p><pre>employees_van_1=[]<br>for v in range(V_vans):<br>  for e in range(E_employees):<br>    if v==0:<br>     employees_van_1.append(str(A[v,e]))<br>            <br>employees_df=results[(results[&#39;Variable&#39;]==&#39;A&#39;)&amp;(results[&#39;Value&#39;]&gt;0)]</pre><pre>display(employees_df[employees_df[&#39;Name&#39;].isin(employees_van_1)])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*cFPytLTo0aeHA9dvL3yO8g.png" /></figure><p>This table tells us that employees 5 and 6 are the ones assigned to the van. Now the final question regarding van 1 is how many boxes and of which products it will have to transport at each of the trips. Let’s do this for the trip from warehouse 2 to store 2:</p><pre>transport_df = results[(results[&#39;Variable&#39;]==&#39;X&#39;)&amp;(results[&#39;Value&#39;]&gt;0)]</pre><pre>transport_trip_2_2 = []</pre><pre>for p in range(P_products):<br>  for w in range(W_warehouses):<br>    for s in range(S_stores):<br>      for v in range(V_vans):<br>        if w==1 and s==1 and v==0:<br>          transport_trip_2_2.append(str(x[p,w,s,v]))</pre><pre>display(transport_df[transport_df[&#39;Name&#39;].isin(transport_trip_2_2)])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*ks9r221pjoSnFCQUnETytA.png" /></figure><p>So, during the trip from warehouse 2 to store 2, van 1 will transport 5 boxes (its maximum capacity), 4 of product 2 and 1 of product 3. Note that during these examples we verified that the model is working as intended i.e. constraints were taken into consideration to obtain the optimal solution. To wrap up, we just need to check what happened with the constraint for the conflicting pair of employees:</p><pre>results[(results[&#39;Variable&#39;]==&#39;G&#39;)&amp;(results[&#39;Value&#39;]!=0)]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*cniC_CSvwB12W0IUaJ4oEA.png" /></figure><p>Well, it looks like the pair of conflicting employees <strong><em>j=14</em></strong> (employees 3 and 4) was assigned to van 2 in the optimal solution. If that’s the case, then A_2_3 and A_2_4 should be equal to 1, let’s check it:</p><pre>results[(results[&#39;Variable&#39;]==&#39;A&#39;)&amp;(results[&#39;Value&#39;]!=0)]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*B7ZtS5qyoUwO70QTc8mZkw.png" /></figure><p>And with that, we finally finished with the examples.</p><h4>Concluding Remarks</h4><p>All in all, we’ve seen that it is indeed possible to write real life problems as systems of linear equations. What’s more, we are also able to solve them. Of course, finding an optimal solution strictly depends on the context variables, the objective and the set of constraints. However, a really complex setting may make finding an optimal solution a much harder process, as more combinations of parameters would need to be analysed, which in turn would require more computing power.</p><p>Finally, even though the example provided in this article relates to a fleet and workforce planning problem, the applications of this framework are much broader. Strictly speaking, I’ve employed this approach to solve problems related to <em>Logistics</em>, <em>Supply Chain Management</em> and <em>Pricing and Revenue Management</em>, but the possible applications go quite further as it is also frequently used to solve problems related to <em>Health Care Optimisation</em>, <em>Urban design</em>, <em>Management Science</em> and <em>Sports Analytics</em>.</p><p>For those who arrived at this point, I hope you were able to obtain some insights to build your own solutions. And don’t worry, even though arguably the hardest part is to define the problem, once you do it, the next steps are quite straightforward. Thanks for reading!</p><h3>References</h3><p>[1] Linear Programming: <a href="https://www.goodreads.com/book/show/56568451-linear-programming">Foundations and Extensions (International Series in Operations Research &amp; Management Science Book 285)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16db08c7f91d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/fleet-and-workforce-planning-with-linear-programming-16db08c7f91d">Fleet and Workforce Planning with Linear Programming</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[A Fuzzy String Matching Story]]></title>
            <link>https://medium.com/data-science/a-fuzzy-string-matching-story-314bbecaa098?source=rss-2939b50adecd------2</link>
            <guid isPermaLink="false">https://medium.com/p/314bbecaa098</guid>
            <category><![CDATA[text-preprocessing]]></category>
            <category><![CDATA[string-matching]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Ezequiel Ortiz Recalde]]></dc:creator>
            <pubDate>Thu, 30 Sep 2021 15:29:03 GMT</pubDate>
            <atom:updated>2023-06-01T07:21:20.861Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to build a fuzzy string matching baseline model</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ksC1QZlcpJHcTUGygqkksg.jpeg" /><figcaption>Photo By Bruno Martins on <a href="https://unsplash.com/photos/4cwf-iW6I1Q">Unsplash</a></figcaption></figure><p>While building a new product based on machine learning applications, we’ll need to extract, collect and store data from different sources. Regardless of the extraction method (APIs, <a href="https://medium.com/@eortizrecalde/a-practical-web-scraping-guide-62073b69b003">web scraping</a> or other), the data collected still needs to go through arguably the most important and time demanding task i.e. integrating, matching and normalizing the data from these sources into a database.</p><p>In this article, we’ll be discussing about <strong>fuzzy string matching</strong>. This problem consists of trying to match strings that are similar yet different (possibly due to spelling differences or mistakes), for example “Lionel Messi” and “L. Messi” or “Argentina” and “Argeentina”.</p><p>But why is this relevant? Let me tell you a story (disclaimer: <em>all characters and events in this article are fictitious and any resemblance to reality, is purely coincidental</em>).</p><h4>The beginning</h4><p>John owns a large chain of kiosks and wants to build more precise pricing models using the prices of their competitors (other kiosks, near stores, and supermarkets). A while ago, he used to pay mystery shoppers to visit and collect price data of some of these competitors every other month, until he realized that this isn’t cost-efficient at all, since prices seem to be adjusted many times each month.</p><p>As soon as realization struck him, he swiftly took action and decided to build a web scraping service that extracted the competitors products’ prices with a higher frequency. After implementing this solution, everything seemed to go well, with the data successfully scraped, John felt he had beaten the system, and thought that his data team would be able to go straight into building new pricing models. However, there was a big problem he hadn’t taken into consideration: the spelling of the scraped products will not necessarily match those of his kiosks’ catalogue, which implies that he wouldn’t be able to directly associate and compare his internal data with the external sources. For example:</p><p>“diet coke 1.5L” ≠ “coke dieet 1500ml”</p><p>So, what did he do after realizing he couldn’t use the data? First, during a sudden rage attack, he broke his keyboard. Later, after calming down, he proceeded to ask his data team if they knew how to solve this problem (using his other keyboard). Seeing the opportunity to gain John’s favor, Carl, the “unicorn” employee, told him that he had worked in similar problems before and could come with an MVP within a week (but truth be told, he had no idea of what he was taking about). John happily agreed but instead of giving Carl just one week to do it, he gave him two.</p><h4>Looking for a solution</h4><p>Using the method that had proven to be effective in the past, Carl used his most reliable tool “Google” to search for “string matching in python”. He soon came across with several posts about matching strings with regular expressions, a new distance he had never heard of called “Levenshtein distance” and the concept of fuzzy string matching. But none of them provided him with a practical solution until he stumbled upon an article called “A Fuzzy String Matching Story” written by some random guy named Ezequiel Ortiz Recalde. This article provided him with some useful advice on how to go through the matching process and build a baseline model through a practical example. We’ll now check what Carl saw.</p><p><strong>1. Imports<br></strong>First we install and import the main libraries to be used to match strings of some beverages that could be found in kiosks or supermarkets (the data was manually generated).</p><pre>#!pip install fuzzywuzzy<br>#!pip install python-Levenshtein<br>#!pip install polyfuzz<br>#!pip install nltk</pre><pre>import pandas as pd<br>import numpy as np<br>import string<br>import re</pre><pre>from nltk.metrics.distance import edit_distance<br>from fuzzywuzzy import fuzz<br>from polyfuzz import PolyFuzz<br>from polyfuzz.models import TFIDF</pre><p><strong>2. The data</strong></p><p>We’ve generated 2 data sets of beverages (external_data and internal_data). The first one refers to external data that could have been obtained by scraping sites, while the second one replicates parts of an imaginary official beverage catalogue of a kiosk. Here we can see a sample of both:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*MzjLLT-7mKESAvxQ5MdFCA.png" /><figcaption>External data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/207/1*clT12TBxqLOZRkeXnomzmQ.png" /><figcaption>Internal data</figcaption></figure><p><strong>3. String preprocessing</strong></p><p>Before even attempting to match strings from different sources, there are some useful transformations that could simplify the problem:</p><ul><li>Turning strings to lowercase;</li><li>Carefully removing symbols and punctuation;</li><li>Removing consecutive blank spaces (or all of them, depending on the problem);</li><li>Cautiously removing stopwords (beware of deleting key words as they could be useful in the future; avoid removing way too many specific words as you still want your model to be able to generalize);</li><li>Standardizing the spelling of different expressions (for example in the case of grams, we could find g, gr, gs, g., gr., gs., etc);</li></ul><p>Following some of these suggestions, we proceed to clean both dataframes’ columns by using the following function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2191ea9eb46a35961e472a2f6960e76/href">https://medium.com/media/f2191ea9eb46a35961e472a2f6960e76/href</a></iframe><p>Before applying the function we create copies of the columns to be modified in order to keep the original versions:</p><pre>external_data[&quot;product_cleaned_from&quot;]=\<br>external_data[&quot;product&quot;].copy()</pre><pre>internal_data[&quot;product_cleaned_to&quot;]=\<br>internal_data[&quot;product_name&quot;].copy()</pre><p>Apply the function to both dataframes:</p><pre>string_processing(df=external_data,columns_to_clean=[&quot;product&quot;])</pre><pre>string_processing(df=internal_data,columns_to_clean=[&quot;product_name&quot;])</pre><p>After doing this, we finally have our clean data to be matched. Next we’ll discuss of the main approach to be used.</p><p><strong>4. String matching with Tf-Idf Vectorization</strong></p><p>Term Frequency Inverse Document Frecuency Vectorization is a technique used in many NLP applications, that aims to approximate the relevance of a word in a document taking into consideration the amount of times it appears in the document and across all the corpus. From this method we get a vector of “weights” for each word in every document, which we can use as features for a classification model.</p><p>But, how does this relate with string maching? Well, we could partition tokens into n-grams and then obtain their TF-IDF vectorization. Once we have vectors of weights of n-grams, we can calculate the similarity between them. Note that this allows us to take advantage of the fast computation of matrix operations relative to the slow process of checking how many edits should be made between each of all the possible pairs of phrases using ratios based on the Levenshtein distance.</p><p>The matching process works as follows:</p><p><strong>a) </strong>Define the 2 lists of strings, 1 list “From” (refers to the content we want to match to something) and 1 list “To” (in this case the catalogue).</p><p><strong>b)</strong> Define the number of n-grams in which the strings will be partitioned.</p><p><strong>c)</strong> Fit the TF-IDF Vectorizer with both lists in order to have a representation of all possible unique n-grams.</p><p><strong>d)</strong> Use the TF-IDF representation, to transform each list to the same representation (if a string doesn’t contain one of the unique n-gram partitions of the vectorizer, then the value for that partition will be 0). From this step, we’ll obtain two matrices of as many columns as unique n-grams partitions (both matrices will have the same amount of columns, as the vectorizer was fit using both lists), with the number of rows referring to the number of elements in each source list.</p><p>Luckily for us, this whole process has been integrated in the <a href="https://maartengr.github.io/PolyFuzz/">PolyFuzz</a> library, but we still want to know if we understood how this works as seeing is believing:</p><p>First we’ll import some functions needed for the explanation:</p><pre>from sklearn.feature_extraction.text import TfidfVectorizer<br>from sklearn.metrics.pairwise import cosine_similarity</pre><p>Next, we generate the lists of strings to match:</p><pre>from_list = [&quot;coke 1.5L&quot;,&quot;sprite zero 1.5L&quot;]<br>to_list = [&quot;diet coke 1.5L&quot;]</pre><p>We slightly modify the function to create n-gram partitions of the tokens used in the <a href="https://maartengr.github.io/PolyFuzz/">PolyFuzz</a> library for it to directly use 3-grams.</p><pre>def _create_ngrams(string: str):</pre><pre>   result = []<br>   for n in range(3, 4):<br>      ngrams = zip(*[string[i:] for i in range(n)])<br>      ngrams = [&#39;&#39;.join(ngram) for ngram in ngrams if &#39; &#39; not in ngram]<br>   <br>   result.extend(ngrams)<br>   return(result)</pre><p>This function receives a string, and for each token separated by white spaces, creates a n sized partition. For example “diet coke” would be split into “die, iet, cok, oke”. Next, we are able to fit the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html">TfidfVectorizer</a> of scikit learn using the <em>_create_ngrams</em> funtion to split the tokens and create the vectorized representation of elements of the lists:</p><pre># Define the vectorizer<br>vectorizer = TfidfVectorizer(min_df=1, analyzer=_create_ngrams).fit(to_list + from_list)</pre><p>Note that there are 2 explicit parameters here <em>min_df</em> and <em>analyzer</em>. The first one refers to the minimum number of times a partition has to appear in the corpus to be included in the vocabulary, while the second one is used to specified how to create the vocabulary of the vectorizer i.e. from words or n-grams.</p><p>Given the input lists we can check the resulting vocabulary.</p><pre>vectorizer.vocabulary_</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/122/1*s4aB_WybULd8MCuY6FeLbQ.png" /></figure><p>The numbers represent the column index of the matrix (“.5L” would be in column 1).</p><p>After creating the matrix representation, we proceed to transform each list to match its structure, receiving sparse matrices:</p><pre>tf_idf_to = vectorizer.transform(to_list)<br>tf_idf_from = vectorizer.transform(from_list)</pre><p>To check the weights of these 3-grams in each row we convert the tf_idf_to and tf_idf_from into dense format, and then into a dataframe using the vocabulary index to set the column names:</p><pre>matrix_from=pd.DataFrame(tf_idf_from.todense(),\<br>columns=sorted(vectorizer.vocabulary_))</pre><pre>matrix_to=pd.DataFrame(tf_idf_to.todense(),\<br>columns=sorted(vectorizer.vocabulary_))</pre><p>Both matrices have size n-elements x n-vocabulary and look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*ZjNeyq9qWbBytYoHIvfMFg.png" /><figcaption>matrix_from</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*RfetaWJDLpuzEv5bsZRJkg.png" /><figcaption>matrix_to</figcaption></figure><p>Now that we have the matrices, we are able to calculate the similarity between vectors of n-grams partitions. In this case we use the cosine similarity:</p><pre>cosine_similarity(matrix_from, matrix_to)</pre><p>with output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*KQHXijWNm8f3PMas1Mh00Q.png" /></figure><p>This gives a similarity score between pairs of vectors of tokens. In this case we can see that “coke 1.5L” is more similar to “diet coke 1.5” than ”sprite zero 1.5L” is. What we’ve just done is the dot product between matrices:</p><pre>np.dot(np.array(matrix_from.iloc[0]),np.array(matrix_to.iloc[0]))</pre><p>returns 0.6936279421797706 while</p><pre>np.dot(np.array(matrix_from.iloc[1]),np.array(matrix_to.iloc[0]))</pre><p>returns 0.1373086119752811.</p><p><strong>5. Additional useful measures: Token set ratio and Levenshtein distance</strong></p><p>We’ve checked just one measure of similarity between strings, but there are also others that might be helpful depending on the type of strings you are comparing. For this particular case, I like to include in the analysis both the token set ratio and the levenshtein distance.</p><p>The token set ratio is a similarity measure of strings, that takes into consideration the repetition of values and the difference in the order of the words (for example, “diet coke” is the same as “coke diet” and for these types of cases we would be interested in catching such direct answers). Let’s see how to calculate it with a simple example “diet coke 1.5ml” and “diet cooke diet 1.5ml” :</p><pre># We create the 2 strings<br>s1=&quot;diet coke 600ml&quot;<br>s2=&quot;diet cooke diet 600ml&quot;</pre><p>i) We start by preprocessing and separating the string into tokens:</p><pre>tokens1 = set(fuzz.utils.full_process(s1).split())<br>tokens2 = set(fuzz.utils.full_process(s2).split())</pre><p>Here tokens1 = {‘600ml’, ‘coke’, ‘diet’}</p><p>ii) Then we take the sets of tokens and obtain their intersection and differences:</p><pre># Intersection<br>tokens1.intersection(tokens2)</pre><pre># Difference (which tokens are we missing so that both sets are equal)<br>diff1to2 = tokens1.difference(tokens2)<br>diff2to1 = tokens2.difference(tokens1)</pre><p>iii) We concatenated the ordered intersections and differences, which solves the problem of the order of the strings:</p><pre>#We concatenate the ordered intersections and differences</pre><pre>sorted_sect = &quot; &quot;.join(sorted(intersection))<br>sorted_1to2 = &quot; &quot;.join(sorted(diff1to2))<br>sorted_2to1 = &quot; &quot;.join(sorted(diff2to1))</pre><p>iv) We combine the tokens inside each option to reconstruct the whole string:</p><pre>combined_1to2 = sorted_sect + &quot; &quot;+ sorted_1to2<br>combined_2to1 = sorted_sect + &quot; &quot;+ sorted_2to1</pre><p>v) We eliminate repeated whitespaces:</p><pre>sorted_sect = sorted_sect.strip()<br>combined_1to2 = combined_1to2.strip()<br>combined_2to1 = combined_2to1.strip()</pre><p>vi) We calculate the fuzz ratio (i.e. the normalized Levenshtein distance) for different pairs of combinations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*oco2RUyE3dQfoD9vstqn8A.png" /><figcaption>Fuzz ratio</figcaption></figure><pre>pairwise = [fuzz.ratio(sorted_sect, combined_1to2)/100,<br> fuzz.ratio(sorted_sect, combined_2to1)/100,<br> fuzz.ratio(combined_1to2, combined_2to1)/100]<br></pre><p>with output [0.8, 0.77, 0.97].</p><p>vii) We keep the pair with maximum fuzz ratio, and its similarity.</p><p>Regarding the Levenshtein distance, we simply use the <em>edit_distance </em>function of nltk. This tells us the numbers of edits needed to change a string into another one.</p><p><strong>6. Building a baseline model</strong></p><p>Now that we’ve got a better understanding of the process, what’s left is to build a pipeline that takes 2 lists, fits a vectorizer with the partitions of their content, calculates the dot product between vectors and match the pair with the highest similarity score. Here’s where the Polyfuzz libraries comes into play, by providing us with a model that follows exactly what we’ve just explained. In addition, we can add some extra information (the token set ratio and the Levenshtein distance) to the end results to avoid having just one way to check the matching quality in a posterior result filtering.</p><p>The whole process is detailed in the following chunk of code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b4e6577b664c7ab61432836331828ea/href">https://medium.com/media/3b4e6577b664c7ab61432836331828ea/href</a></iframe><p><strong>7. Results</strong></p><p>Here’s a sample of the results obtained, you can explore the rest by checking the <a href="https://github.com/eortizrecalde/string-matching/blob/main/string_matching.ipynb">notebook</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qPqC-loHgBvIxsR9S4WyNA.png" /></figure><p><strong>8. Concluding remarks</strong></p><p>In this brief article, we’ve presented a simple framework that may be capable of producing decent results for any fuzzy string matching problem (at least that was the case for me). Regardless of the kiosk product’s example, this should aid you whenever you need to match non normalized or free text with some sort of catalogue or reference that has been ideally validated by the business.</p><h4>The end</h4><p>After reading it, before proceeding to solve his matching problem Carl did what everyone would do i.e. he liked and shared the article 😉.</p><h3>References</h3><ul><li><a href="https://en.wikipedia.org/wiki/Approximate_string_matching">Approximate string matching - Wikipedia</a></li><li><a href="https://openclassrooms.com/en/courses/6532301-introduction-to-natural-language-processing/7067116-apply-the-tf-idf-vectorization-approach">Apply the TF-IDF Vectorization Approach</a></li><li><a href="https://github.com/MaartenGr/PolyFuzz">GitHub - MaartenGr/PolyFuzz: Fuzzy string matching, grouping, and evaluation.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=314bbecaa098" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/a-fuzzy-string-matching-story-314bbecaa098">A Fuzzy String Matching Story</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[A Practical Web Scraping Guide]]></title>
            <link>https://medium.com/@eortizrecalde/a-practical-web-scraping-guide-62073b69b003?source=rss-2939b50adecd------2</link>
            <guid isPermaLink="false">https://medium.com/p/62073b69b003</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Ezequiel Ortiz Recalde]]></dc:creator>
            <pubDate>Thu, 10 Jun 2021 19:32:21 GMT</pubDate>
            <atom:updated>2021-06-10T19:32:21.420Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn to navigate and scrape dynamic websites with Selenium and Scrapy by extracting cryptocurrency data</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VMTosXdPjDGd6M3tqLKC-A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@kristapsungurs?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Kristaps Ungurs</a> on <a href="https://unsplash.com/s/photos/spaceship-launch?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>If you aren’t new to data science you may have already come to the realization that you don’t always have the data you need to solve a problem. So, what do you do when you don’t have the information you need? You could resort to web scraping, but before you do there are some relevant points to take in consideration.</p><p><strong>What are we doing when we scrape a website?</strong> Web scraping can be defined as the process of extracting the content of a website by programming bots to make different requests of data in HTML or XML and in some cases mimic human interaction (like clicking or moving the pointer to access certain elements that aren’t available at first sight, such as the content of dropdown menus).</p><p><strong>Can we freely scrape the content of any site?</strong> We should always first check the site’s robots.txt by adding “/robots.txt” at the end of the main url. This file specifies the parts of the website that each user can scrape, and in some cases the rules they should follow while doing so. In short, if in the txt for “user agent: *” you see either “Allow: /” or an empty “Disallow: ”, there’s no restrictions placed on generic users (for further information about how to interpret it you could check Google developers <a href="https://developers.google.com/search/docs/advanced/robots/create-robots-txt">documentation</a> on how to create a robots.txt). However, even if we find that there are no restrictions, we should still be careful with the amount of requests we are making.</p><p><strong>Are there any issues that may stop us from scraping data for extended periods of time?</strong> Yes, as we are extracting HTML/XML content, if there is any change in the website’s design/structure/naming of elements, our script is set to fail. Nevertheless, we could take some measures to make our code flexible enough to cope with some minor changes:</p><ul><li>Prioritize searching by xpaths instead of just using class names or ids;</li><li>If possible avoid using too many filters on the paths;</li><li>Follow the shortest path to reach the data you need;</li><li>Manage errors and exceptions by providing alternative actions;</li><li>When filtering by a matching text, use contains, starts-with or ends-with.</li></ul><p><strong>What Python Libraries should you use?</strong> I tend to combine <a href="https://selenium-python.readthedocs.io/">Selenium</a> with <a href="https://docs.scrapy.org/en/latest/">Scrapy</a>, as this allows for a more functional and flexible scraper. Even though Selenium is mainly designed to test web-based applications, it is particularly useful to scrape dynamic websites. Scrapy, on the other hand, was specifically created to scrape websites really fast, but falls short when working with dynamic sites.</p><h3>A practical case: Cryptocurrency data</h3><p>For this guide we’ll be scraping <a href="https://coinmarketcap.com/en/">Coinmarketcap</a>, a website that contains data of several cryptocurrencies. This example is expected to provide you with enough tools to tackle most of web scraping simple problems, as they commonly consist of browsing through different elements of a site, filling forms, scrolling, selecting items of hidden menus, closing pop-up elements and extracting content, all by inspecting various paths. An enhanced version of the full code can be found in the following github <a href="https://github.com/eortizrecalde/web-scraping/blob/main/scraping_example.ipynb">repository</a>:</p><h4>1- Install and import libraries</h4><pre># General libraries<br>import pandas as pd<br>import numpy as np<br>import time</pre><pre># String preprocessing<br>import re<br>import string</pre><pre># Scraping tools<br>from selenium import webdriver<br>from selenium.webdriver.common.action_chains import ActionChains<br>from scrapy import Selector</pre><h4>2- Chromedriver installation on Linux and Windows</h4><p>To be able to use Selenium, we first need to download a WebDriver controller. This will allow us to interact with a website as if we were a real user. Selenium supports several browsers such as Firefox, Internet Explorer, Opera, Safari and Chromium (Chrome). In this case we’ll be using Chromium.</p><p>If you work with Linux like myself, you should run the following commands on the terminal:</p><pre>sudo apt-get update -y<br>sudo apt-get install chromium-chromedriver</pre><p>If you are a Windows user, download Chromedriver from the following url <a href="https://chromedriver.chromium.org/downloads">https://chromedriver.chromium.org/downloads</a>. The version you have to install must match your current Chrome version. To know which version you have, open your Chrome browser, and enter “chrome://settings/help” on the search bar. You’ll be able to find the version below the title “About Chrome”. In my case I have Version 90.0.4430.212.</p><p>Once you’ve installed it make sure to either save the executable on your working directory or identify the path where it was saved. We’ll need this in the following step.</p><h4>3- Specify the webdriver and open the website to scrape</h4><p>First of all, we have to set up the chromedriver. Before calling it, we can choose it’s initial configuration, i.e. starting with a maximized window, using a headless browser, or specifying a proxy server. Note that each driver has a different way of setting the options so if you decide to use another browser such as Firefox, you’ll need to check for the specific documentation.</p><p>After that, we declare that we’ll be using Chrome, and set the path of the chromedriver (in this case it’s in the working directory so we just type “chromedriver”). Next we call the url by making a request using the browser class instance. This will open a Chromium window with the url we’ve passed.</p><pre># Set the browser to start maximized<br>custom_options = webdriver.ChromeOptions()<br>custom_options.add_argument(&quot;--start-maximized&quot;)</pre><pre># Call the driver and pass the custom options<br>browser=webdriver.Chrome(executable_path=&quot;chromedriver&quot;,\<br>options=custom_options)</pre><pre># Specify and open the url you want to access<br>url= &quot;<a href="https://coinmarketcap.com/en/&#39;">https://coinmarketcap.com/en/</a>&quot;<br>browser.get(url)</pre><p>You should be seeing something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u4r2DVslsfvFpPq2tGgCZg.png" /></figure><p>Now that we are in the main site, we’d like to first picture where is the data we want and how can we efficiently reach it. For example, if we’d like to get historic data on a specific currency, we have 3 possible paths:</p><p><strong>A)</strong> Click the name of the cryptocurrency if it’s on the main page, select the “Historical Data” option and choose the date range.</p><p><strong>B)</strong> Go to the search box, enter the token abbreviation, select the “Historical Data” option and then choose the date range.</p><p><strong>C)</strong> Instead of accessing the main site, directly go to the historical data page and then choose the date range.</p><p>Which one should you choose? That depends on your objective. If you’d like to get data on many currencies you’ll probably be better off by always starting from the main site and then looking for the token in the search box. However if you are only interested in one crypto, going straight to the specific url will be more efficient.</p><p>We’ll proceed with option <strong>B)</strong>, to extract data of Bitcoin (BTC), Ethereum (ETH), Cardano (ADA) and Dogecoin (DOGE).</p><h4>4- Access the XML paths to the relevant content of BTC</h4><p>As mentioned at the beginning, while scraping websites we are extracting the HTML/XML used to build the website. In order to see it, right-click anywhere inside the site and click the “inspect” option. This will open the developer tools on the right side of the window with the site’s elements. Alternatively, depending on your keyboard configuration, you could just press F12.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VENqvmzk5cvGKjjP0ccA3A.png" /></figure><p>Now, we need to find the XML path used for the search box. We can do this by repeating the “inspect” procedure but this time, right clicking the search box. From this we learn that the Search box path looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*S4ytezE0HjLUb5qBRFlEJw.png" /></figure><p>But… there’s no direct path to enter the token we’d like to search since this is a dynamic website. So, we first have to click the search box to be able to see the path used to send content. Here you have two ways of clicking the search box element:</p><pre># By using the text inside the div element<br>browser.find_element_by_xpath(&quot;//div[contains(text(),\<br>&#39;Search&#39;)]&quot;).click()</pre><pre># By using the class name of the div element<br>browser.find_element_by_xpath(&quot;\<br>//div[<a href="http://twitter.com/class">@class</a>=&#39;q0coyt-1 fOZYHf&#39;]&quot;).click()</pre><p>In both cases, we are using the method “find_element_by_xpath” to look for the first WebElement that matches a path. Inside the method, we start by writing “//” which means we’ll be calling a path that has an element (in this case a div) regardless of what came before. Next we filter the element by some condition.</p><p>With the first option we look for the div element that contains the string “Search” (if you’d like to look for an element that starts with “Search” you can replace “contains” for “starts-with”, the same goes for “ends-with”). The other alternative looks for the path that has a div with a specific class. Note that if we wanted to pick all the elements with a certain path, we could use “find_elements_by_xpath”, which returns a list of WebElements.</p><p>Now that we’ve clicked the search box we can inspect again the element to look for the path to send the content we want to look for:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*rVPI4ssyA2ANiHA8JvwJLQ.png" /></figure><p>Next we need to give this path to the browser object and send the string of the token:</p><pre># Find the opened search box element by searching the placeholder<br>opened_search_box=browser.find_element_by_xpath(\<br>&quot;//div/input[<a href="http://twitter.com/placeholder">@placeholder</a>=&#39;What are you looking for?&#39;]&quot;)</pre><pre># Specify what we want to look for<br>token = &quot;BTC&quot;</pre><pre># Send the token and press enter<br>opened_search_box.send_keys(token+ &quot;\n&quot;)</pre><p>Note that we first save the “opened” search box element and then fill it by sending the token and adding a “\n” which works as a keyboard ENTER button.</p><p>After that, we’ll be seeing the Bitcoin page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vrBtx3VUrc4f2r1qeXy1_Q.png" /></figure><p>We then look for the “Historical Data” section, which happens to be at:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*BJvHGCv2aifvP5Pzy1r2Cg.png" /></figure><p>We click it:</p><pre>browser.find_element_by_xpath(&quot;//a[contains(text(),\<br>&#39;Historical Data&#39;)]&quot;).click()</pre><p>Next we’d like to click the “Date Range” button to select the period of data we want to extract, but a cookie banner might appear over it so we have to close it before proceeding. To do this, if the banner popped up, we look for it’s path and click it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*Pez5oA3O77TWfwDxrUf8bw.png" /></figure><pre>browser.find_element_by_xpath(&quot;//div[<a href="http://twitter.com/class">@class</a>=&#39;cmc-cookie-policy-banner__close&#39;]&quot;).click()</pre><p>Now we can look for the “Date Range” button’s path :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*egKJURU7c88kGQZ2uN--tg.png" /></figure><p>Click it:</p><pre>browser.find_element_by_xpath(&quot;//button[contains(text(),\<br>&#39;Date Range&#39;)]&quot;).click()</pre><p>Inspect the predefined date ranges and choose one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*4pLyy6bJYBshP_tFfs07vw.png" /></figure><p>We select the longest period:</p><pre># Select the 365 days date range<br>browser.find_element_by_xpath(&quot;//div[<a href="http://twitter.com/class">@class</a>=&#39;predefinedRanges___1WDIZ&#39;]/ul/li[contains(text(),&#39;365&#39;)]&quot;).click()</pre><pre># Click the continue button<br>browser.find_element_by_xpath(&quot;//button[contains(text(),\<br>&#39;Continue&#39;)]&quot;).click()</pre><p>Note that in this case we’ve added two filters to the Date Range button path, a class filter for the div, and a text filter for the element of the list. You should always try to avoid using many filters, as the exposure to minor web changes increases the more restrictions you impose on your request. In this case, the following would have been better:</p><pre>browser.find_element_by_xpath(&quot;//div/ul/li[contains(text(),\<br>&#39;365&#39;)]&quot;).click()</pre><p>What if we wanted more than 365 days of data? We could either try to select a customized period or simply click the “Load More” button at the end of the page as many times as necessary. We’ll try the latter as you’ll probably face scenarios where there are no predefined filters available.</p><p>First, to make sure the button is reachable (sometimes we need it to be visible in order to click it), we scroll to the bottom of the page by using the execute_script method to run a javascript instruction:</p><pre>browser.execute_script(&quot;window.scrollTo(0,document.body.scrollHeight);&quot;)</pre><p>The first term of “scrollTo” refers to the x-axis and the second one to the y-axis. If you wanted to scroll to an arbitrary height, you could use positive or negative values (positive for top-down and negative for bottom-up scrolling):</p><pre>arbitrary_height=10<br>browser.execute_script(f&quot;window.scrollTo(0, {arbitrary_height});&quot;)</pre><p>Now that we are sure we can reach the “Load More” button, we write a loop where we scroll to the bottom of the page each time we click it.</p><pre>for i in range(10):<br>    browser.find_element_by_xpath(&quot;//button[contains(text(),&#39;Load More&#39;)]&quot;).click()<br>    time.sleep(np.random.uniform(1.1,1.2))<br>    browser.execute_script(&#39;window.scrollTo(0,document.body.scrollHeight);&#39;)<br>    time.sleep(np.random.uniform(1.1,1.2))</pre><p>You’ll notice that between each action there are pauses of random intervals (in seconds). This is a good practice to follow, as it gives time for the page to respond and allows you to adjust the scraping speed to avoid sending too many requests in a short period of time.</p><h4>5- Extract the data</h4><p>We’ve finally loaded the page that contains the table with all the historical data we wanted:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jLMVZpaPA7mO_sWCZLyyVg.png" /></figure><p>We’ll proceed to extract it by briefly making use of Scrapy. In the following chunk of code, we get the complete HTML content of the current page by using the page_source method of Selenium. Then, we use Scrapy’s <a href="https://docs.scrapy.org/en/latest/topics/selectors.html">Selector</a> to query the desired parts of the source. As we’ll see, this provides a fast and easy data extraction experience.</p><pre># Define the Scrapy Selector object<br>selenium_response_text = browser.page_source<br>scrapy_selector = Selector(text=selenium_response_text)</pre><p>After inspecting the path to the table’s rows and columns following the previous method, we start with the extraction:</p><pre># Get the names of the columns<br>col_names = scrapy_selector.xpath(&quot;//table[contains(<a href="http://twitter.com/class">@class</a>,\<br>&#39;cmc-table&#39;)]//th/text()&quot;).getall()</pre><pre># Get the number of columns<br>n_columns = len(col_names)</pre><pre># Get the row values<br>rows_values=scrapy_selector.xpath(&quot;//table[contains(<a href="http://twitter.com/class">@class</a>,\<br>&#39;cmc-table&#39;)]//tr/td/text()&quot;).getall()</pre><pre># Convert list to array<br>rows_array=np.array(rows_values)</pre><pre># Specify the number of equally sized chunks<br>number_of_chunks=len(rows_array)/n_columns</pre><pre># Make the partitions<br>partitions=np.array_split(rows_array, number_of_chunks)</pre><pre># Create the DataFrame<br>df=pd.DataFrame(data=partitions,columns=col_names)</pre><pre># Save the token associated with this extraction<br>df[&quot;Token&quot;]=token</pre><p>As you can see, to get the data from the table we use the Scrapy Selector’s method “xpath”. The syntax is almost the same as Selenium’s “find_element_by_xpath”. However, we can now directly get the text by specifying “/text()” at the end of the path (if you’d wanted to extract the class you could place “/@class instead” of “/text()”).</p><p>During the process we get the number of columns, their names and the row values (a list that has all the rows together). As per the extraction, we know that we have 7 columns, so the row values list could be broken down into partitions of size 7 to distinguish the sequence of values that belong together. Then, we turn the list into an array to obtain the number of equally sized chunks, make the partition and create the DataFrame.</p><h4>6- Extend the working example to other tokens</h4><p>After making sure the pipeline works for a specific case, we’ll turn the previous steps into a function that can gather historical data of other coins. You can check the “historical_data” function in the <a href="https://github.com/eortizrecalde/web-scraping/blob/main/scraping_example.ipynb">repository</a>.</p><p>Run the function for several tokens:</p><pre># Specify the tokens to look for<br>tokens=[&quot;BTC&quot;,&quot;ETH&quot;,&quot;ADA&quot;,&quot;DOGE&quot;]</pre><pre># List to save DataFrames<br>token_data=[]</pre><pre>for token in tokens:<br>    token_data.append(historical_data(token=token,<br>                      timeframe=365,<br>                      max_loadings=10))</pre><pre>results=pd.concat(token_data).reset_index(drop=True)<br>results.sample(8)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*ogAasdtvpGIoW32XLm3iEQ.png" /></figure><h4>7- Bonus: Get the top 24hr Gainers</h4><p>To showcase other Selenium functionalities, we’ll get the top 24hr Gainers data. To achieve this we first need to place the pointer over the “Cryptocurrencies” button.</p><pre>button=browser.find_elements_by_xpath(&quot;//span[contains(text(),<br>\&#39;Cryptocurrencies&#39;)]&quot;)[0]</pre><p>Once again we repeat the inspect process to find the path, and then save the WebElement into the “button” object. Here we are using the “find_elements_by_xpath” method, and as we receive a list, we have to specify the element we want to save (note that this is helpful when we have several items that match the same path, and we want to get a particular one).</p><p>Given that we now have the button to which we’d like to hover over, we call Selenium’s ActionChains class. You can use it whenever you need to mimic complex behaviour such as hovering over menus or items to display hidden content that wouldn’t be available just by clicking the element.</p><pre># Define an instance of ActionChains that takes the browser<br>action=ActionChains(browser)</pre><pre># Pass the button to the action object and perform the move action<br>action.move_to_element(button).perform()</pre><pre># Give a random time wait to continue <br>time.sleep(np.random.uniform(1.5,2))</pre><pre># Click the Gainers &amp; Losers options in the hidden menu<br>browser.find_element_by_xpath(&quot;//h6[contains(text(),\<br>&#39;Gainers &amp; Losers&#39;)]&quot;).click()</pre><p>Now that we are in the “Gainers &amp; Losers” section, we can see that there are 2 tables (one for the Top Gainers, and another one for the Top Losers). So we need to specify which table to scrape. For this example we’ll look for the Top Gainers data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*HwuHtIfzKa2BsOx6ajvLMA.png" /></figure><p>Here we have to specify that an h3 element that comes after a div must match the text “Top Gainers” and then, 2 levels below the div we have to look for a table with a class that at least contains “cmc-table”. We then proceed to extract the column and row data but without using Scrapy’s Selector:</p><pre>token_type=&quot;Top Gainers&quot;</pre><pre># Identify the columns and rows paths for the desired token_type <br>columns_path = browser.find_elements_by_xpath(f&quot;\<br>//div/h3[contains(text(),\<br>&#39;{token_type}&#39;)]/..//table[contains(<a href="http://twitter.com/class">@class</a>,&#39;cmc-table&#39;)]//th&quot;)</pre><pre>rows_path = browser.find_elements_by_xpath(f&quot;\<br>//div/h3[contains(text(),\<br>&#39;{token_type}&#39;)]/..//table[contains(<a href="http://twitter.com/class">@class</a>,&#39;cmc-table&#39;)]//tr/td&quot;)<br> <br># Get number of columns and their name<br>columns=[]<br>for column in columns_path:<br>   columns.append(column.get_attribute(&quot;textContent&quot;))</pre><pre>n_columns=len(columns)</pre><pre># Get the rows values<br>rows_values=[]<br>for row in rows_path:<br>   rows_values.append(row.get_attribute(&quot;textContent&quot;))</pre><p>In summary, we get the paths for the columns and rows, and then iterate through the elements in each of them. With each iteration we extract the text of the element by using the method get_attribute (if instead you wanted to extract a property value of an element such as the class or the id, you could use the method get_property).</p><p>We repeat the same for the tokens:</p><pre># Extract the tokens<br>tokens_path=browser.find_elements_by_xpath(f&quot;//div/h3[contains(text(),\&#39;{token_type}&#39;)]/..//table[contains(<a href="http://twitter.com/class">@class</a>,&#39;cmc-table&#39;)]\<br>    //tr/td//p[<a href="http://twitter.com/color">@color</a>=&#39;text3&#39;]&quot;)</pre><pre>tokens=[]<br>for token in tokens_path:<br>  tokens.append(token.get_attribute(&quot;textContent&quot;))</pre><p>Finally we ensamble the results like in the previous example:</p><pre># Specify the size of the chunks to partition the list of row values<br>rows_array=np.array(rows_values)<br>size_of_chunks=len(rows_array)/n_columns</pre><pre># Make the partitions<br>partitions=np.array_split(rows_array, size_of_chunks)</pre><pre># Create the DataFrame and add the token column<br>df=pd.DataFrame(data=partitions,columns=columns)<br>df[&quot;Token&quot;]=tokens</pre><p>For the last step, we clean the “Name” column that had the token name concatenated and show a preview of the results:</p><pre>df[&quot;Name&quot;]=df.apply(lambda s: re.sub(f&#39;{s[&quot;Token&quot;]}$&#39;, &quot;&quot;, s[&quot;Name&quot;]),axis=1)</pre><pre>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*9_AYJ0Sa6sW_icCt7gbG0w.png" /></figure><p>A complete function to change periods and select the Top Losers is provided in the <a href="https://github.com/eortizrecalde/web-scraping/blob/main/scraping_example.ipynb">repository</a>.</p><h4>Concluding remarks</h4><p>In this short guide we explored the main functionalities provided by Selenium to manage dynamic websites. We’ve seen that this tool can be used to mimic human actions such as scrolling, hovering over an element, sending keys to a search form, and extracting data. Furthermore, we showed an example of how to combine Scrapy’s Selector with Selenium, for a faster scraping experience.</p><p>Hopefully you’ll be able to incorporate some of this in your next scraping project!</p><h3>References</h3><ul><li><a href="https://selenium-python.readthedocs.io/">Selenium documentation</a></li><li><a href="https://docs.scrapy.org/en/latest/topics/selectors.html">Scrapy documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62073b69b003" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>