<?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 AleAlejandro1 on Medium]]></title>
        <description><![CDATA[Stories by AleAlejandro1 on Medium]]></description>
        <link>https://medium.com/@AleAlejandro1?source=rss-685474db29ea------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2I0TxvnmWotE9Fd8qfSOvg.jpeg</url>
            <title>Stories by AleAlejandro1 on Medium</title>
            <link>https://medium.com/@AleAlejandro1?source=rss-685474db29ea------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 21:06:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@AleAlejandro1/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[“The Bots Are Here. Now What?” 
How Knowledge Management Became the Key to Powering GenAI Solutions]]></title>
            <link>https://medium.com/dsaid-govtech/the-bots-are-here-now-what-how-knowledge-management-became-the-key-to-powering-genai-solutions-913452fb71b8?source=rss-685474db29ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/913452fb71b8</guid>
            <category><![CDATA[knowledge-management]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[bots]]></category>
            <dc:creator><![CDATA[AleAlejandro1]]></dc:creator>
            <pubDate>Wed, 06 Aug 2025 09:32:19 GMT</pubDate>
            <atom:updated>2025-08-06T09:32:19.711Z</atom:updated>
            <content:encoded><![CDATA[<h3>“The Bots Are Here. Now What?” <br><em>How Knowledge Management Became the Key to Powering GenAI Solutions</em></h3><h3><strong>1. Introduction: The Arrival of the Bots</strong></h3><p><em>TL;DR: Available LLMs are powerful enough. What we are missing is the </em><strong><em>knowledge</em></strong><em> to fuel them.</em></p><p>As far as Machine Learning (ML) was concerned, the years around 2020 were spent sharpening the tools to continue to do the same type of work, but more professionally. LinkedIn was full of articles on “what is the difference between supervised and unsupervised learning” and colleagues were discussing whether Machine Learning Engineer and Data Scientist were the same role. At the time, much of the operations part of ML were shaping up, giving us the MLOps we all now know. Let’s just say that ML maturity is pretty high right now.</p><p>Fast forward, from 2023 to now (July 2025) things have changed. The future is here, and the robots have arrived. Online, I see a lot of focus on the quantifiable aspects (e.g. evals where model A is 5% better than model B, hence model A is king and model B is a jester). Initially, I tried to keep up with news and comparisons, but I have to admit that since Llama 3 was released I stopped paying attention to the LLM race. Sure, open, cheaper and faster is always welcome, but I can tell that the bottleneck has shifted from the quality of the models to <em>us</em>. The robots have arrived.. and we are not ready for them.</p><p>This realisation came when I started working on a chatbot project in 2024. I was lucky to have the opportunity to test out the freshly released<a href="https://aibots.gov.sg/"> AIBots</a> (a chatbot-builder-platform, courtesy of GovTech’s Government Digital Products (GDP)) and was able to build a proof of concept in literally under 15 minutes. The team at AIBots did an outstanding job then and have been able to continuously top themselves ever since. As a user of AIBots, I felt that by abstracting away the hardening, model hosting, knowledge chunking, embedding and Retrieval Augmented Generation (RAG) systems, all I was left with was the keys to a spaceship. I only needed to provide the “fuel”, which was the knowledge, and AIBots would handle the rest. Surely the knowledge was the easy part. Right?</p><h3><strong>2. The Forgotten Discipline: Knowledge Management</strong></h3><p><em>TL;DR: Enterprise knowledge management is not a new problem, but thanks to GenAI, motivation to address it is now sky-high</em>.</p><p>While refining my proof of concept (which took longer than 15 mins) I got greedy and the knowledge I tried to squeeze in started growing and so did my struggle to organise it. It was during the recycling of a mixture of documents in various formats, that I started to discern the unique qualities of the task itself. So, I did a little digging on the internet. Turns out Knowledge Management is a field of work (the term only coming out in the 90s), but the practice has been there since we could paint in caves.</p><p>And, both from what I was experiencing and from reading online, let me tell you this: knowledge management is hard too. People seem to have always thought of the idea of knowledge management as valuable but largely neglected the implementation. “The search doesn’t work well”, “the content is stale”, “there is no ownership on the documents”. These were all problems I was facing in my little proof of concept too!. How to scale up?</p><h3><strong>3. Why KM Matters More Than Ever</strong></h3><p><em>Tl;DR: Taking the coding part seriously and not the knowledge management seriously will simply not work for real world usage.</em></p><p><a href="https://www.linkedin.com/posts/kozyrkov_the-most-important-difference-between-a-chatbot-activity-7334208625487351810-Tfwk/">Like Cassie says</a>, <em>a chatbot can only harm you if you let it</em>. But have I mentioned agents? It’s been proclaimed that 2025 is the year of agents. Agents who can take actions and are earnest for detailed SOPs, corner-case catching instructions and a wide range of examples of “what good looks like”. Yet, as I witnessed these powerful LLMs and agents figuratively marching towards our project, we found ourselves squat-stirring at a stew of stale Power Points, PDFs and various chunks of text that I copy pasted from my company’s intranet into a variety of TXT files. We were not ready.</p><p>And that’s the point I’m hoping to make here. Your solution leveraging a bot/agent/whateverAI is as good as the content that powers it. The LLMs we have now are more than sufficient for the task. The vector databases that power the similarity search are perfectly well suited to pull out the correct<em> top-K</em> references, that is, if you have those references in the first place. You can only do useful RAG if you have something worth R-ing.</p><p>Realising that the LLMs were not going to do most of the heavy lifting, we changed gears dramatically. We decided that if our chatbot was going to work effectively, we needed to treat all parts of the process with equal importance. If Machine Learning could have an MLOps, we were going to have a KnowledgeOps. And aside from generic statements and frameworks, we couldn’t find a specific stack or SOP to implement online, so we made our own.</p><h3><strong>4. Our KnowledgeOps</strong></h3><p><em>TL;DR: You cannot wing it with knowledge management. Define an SOP and stick to it.</em></p><p>It goes without saying that what works for us might not work for you. However, these recommendations should be implementable in whatever tech stack you have at your workplace. Our process is presented in Figure 1 below.</p><ul><li><strong>Markdown</strong>: Simple and plain. Transparent and less prone to malicious prompt injections. You can perform RAG based on Markdown chunks, which gives a visually-friendly retrieval flexibility that a fixed chunk-size never could.</li><li><strong>Version Control with Git</strong>: When we keep a development and production version of our markdown files, we might end up with multiple versions of docs and rounds of revision. How is this not like code? We could even do unit tests against the knowledge, if we liked.</li><li><strong>Development and Production Bots</strong>: Never test knowledge changes in production. Do I need to say more?</li><li><strong>Review Cycles and Hotfixes:</strong> You need to include metadata like “date_last_updated” or “content_status”. This will help you orchestrate periodical freshness updates and checks. Even if nothing has changed, your user will appreciate that fresh timestamp. There will be a need for hotfixes, so do plan for them too.</li><li><strong>Testing</strong>: Remember when you thought that explaining <em>precision</em> and <em>recall</em> was complicated? Simpler times <em>indeed</em>. What works for us is coming up with a set of questions that cover all important domains in the knowledge base. As we add more knowledge, we add more questions and involve experts who can assess the veracity of the answers to those questions. After various scorings and quantifications, we find ourselves satisfied with knowing the bot said either “correct information” or “abstained from answering” most of the time. Your boss can decide what % “most of the time” should be, provided that the number is strictly less than the FTE (Full Time Equivalent a.k.a workload) % of the knowledge curator.</li><li><strong>Monitoring</strong>: Once your bot is out in the wild, you must observe its interaction with the humans it meets. Here’s where having access to anonymised interaction is golden. You get to observe how people engage with your bot organically. Do they expect the bot to know a domain you haven’t covered? Do they know how to prompt the bot? Has someone found your bot’s Achilles’ heel? AIBots platform offers this feature and without it, we wouldn’t know what’s going on.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yQ_BriYYODv-8_LR" /><figcaption><em>Figure 1. Our KnowledgeOps SOP, from Markdown Knowledge, all the way to production, monitoring and back at Markdown Knowledge.</em></figcaption></figure><h3><strong>5. The Role of the Knowledge Curator</strong></h3><p><em>TL;DR: If you have a data product that requires someone to make it work, you need to make someone responsible and empowered to own it.</em></p><p>Maybe you are reading this and thinking: “This is all fine and dandy, but who’s going to be doing all this work?”. Well, a knowledge manager. Sometimes known as a librarian, curator or information organiser. Someone needs to fuel the spaceship so the rest can enjoy the ride. Let’s talk a bit more about this someone. Here are some traits that they should possess:</p><ul><li><strong>A Steward</strong>: This job role doesn’t have to be a full time position but needs someone who is explicitly assigned the responsibilities and is well empowered to carry them out. If your subject matter expert won’t collaborate with the knowledge manager, the role is not set for success. And that goes for your AI solution too.</li><li><strong>Responsibilities</strong>: Define and maintain a style, strive for clarity and simplicity, deduplicate relentlessly, maintain freshness and metadata hygiene. You will also have to plan for new content intake schedules (which involves testing, development and deployment). Housekeeping too.</li><li><strong>Skillset</strong>: Software development background is certainly not a requirement, but it can help get the intuition and tools quickly. More <em>importanter</em>, is excellent written communication, social predisposition to pick the brains of subject matter experts and vanilla project management.</li></ul><p>And just like that, for all the AI Doomersayers, we’ve just created a new job role for a human thanks to GenAI. Didn’t see that one coming.</p><h3><strong>6. Conclusion: What should you do?</strong></h3><p><em>TL;DR: Big knowledge management requires a plan and collaboration. Do you have one?</em></p><p>If everything your bot has to say can fit in a couple of A4 pages, you probably don’t need any of this. But, if you are covering multiple complex topics, that require various degrees of depth and abstractions, and the span of those topics is growing, you will need to invest some effort in managing your knowledge.</p><p>An important byproduct of collaborative knowledge management, is that the process of organising the knowledge helps teams better understand the problem. There’s a<a href="https://www.intercom.com/blog/guide-customer-service-knowledge-management-ai/"> company</a> that approaches this by having experts observe the challenges their users face and has them hammer out blog posts that can be used as knowledge for chatbots. By releasing and editing existing blogs in response to user’s challenges or ahead of new launches, they set their bot for success, and in this way their company too.</p><p>Your knowledge, just like the rest of your data, is an important resource and one that can make or break your GenAI solution. If you are serious about LLMs, Context Engineering and Agents, you need to be serious about knowledge management. LLMs may have read every article on Wikipedia and Reddit, but the realm of your solution is specific and if you don’t build a fence around your context in crystal clear fashion, you will get generic slop. It’s not a bug or a hallucination, it’s how it works. The more you treat your LLM as the smart parrot that it is and less like a knowledgeable reputable source, the more you will see the benefits of having a knowledge base to RAG-on.</p><p>The best time to set up your knowledge base was 5 years ago, the next best time is now. Define your scope, empower your knowledge manager and get to work on your knowledge management today.</p><h3><strong>7. <em>MY</em> templates are <em>YOUR</em> templates</strong></h3><p>Here’s a skeleton of what our documents look like. Again, your version might require adjustments but keep these content bits below as suggestions:</p><pre>- - <br>title: &quot;[Document File Name]&quot; <br>date_last_updated: &quot;YYYY-MM-DD&quot; <br>content_status: &quot;[DRAFT/APPROVED/ARCHIVED]&quot; <br> - - <br> <br># Executive Summary <br>&lt;! - AI-generated executive summary of the document content → <br> <br> <br># Main Content <br>&lt;! - Brief overview of the sections of the document and how they connect to one another. It&#39;s ok to be redundant, remember that the semantic search will perform better if you name your entities consistently. →<br><br>## Section 1 <br>&lt;! - Content here →<br>&lt;! - URLs using markdown like [THIS](link) → <br> <br>### Subsection 1.1 <br>&lt;! - Content here →<br>## Section 2<br>&lt;! - Content here →ma</pre><h3><strong>8. Epilogue: Useful tips</strong></h3><p>Here are the two most important tips:</p><ol><li>Public sector work requires very high accuracy. The advice and guidelines on prompt engineering, user query and knowledge management all help with reducing LLM hallucinations. But don’t forget the most important thing you can do: <em>managing expectations</em>. No one should expect perfect answers from an LLM.</li><li>Remember that nobody wants to converse with a chatbot if they can avoid it. Especially at work. Make sure people get what they need as painlessly as possible.</li></ol><p>Here’s a non-ranked list of tips and learnings we found useful. Hope you can find something that helps you too:</p><ul><li>If your solution is intra-company facing and you have an intranet, work to make your intranet <em>the</em> knowledge base. Nothing beats providing links to “the source” after every statement of the bot.</li><li>Avoid non-text references. If you have a very cool chart, you will have to describe it and provide a link to it. Large Multimodal Models (LMMs) are not as reliable, lightweight and easy to handle as LLMs. At least for now.</li><li>Like with any product, define your user and build a fence around its needs. This will in turn help narrow down the scope of the knowledge that you need to manage.</li><li>Don’t try to automate something that a human couldn’t do (with enough time and motivation). If you are asking your chatbot questions that would make a subject matter expert pause and hesitate, your bot will fare far worse.</li><li>A lot of people are still learning how to prompt adequately. You can use some of your benchmark questions as “suggested questions” for them to get started. These also help illustrate the boundaries of the knowledge base.</li><li>Make your knowledge base available to your users. We position our chatbot as a guide, whereas the knowledge base itself is the authoritative source of information. Providing clickable reference links to the knowledge after a bot finishes the statement really helps solve a lot of questions.</li><li>Abstaining from answering is not a failure. Letting the bot go ahead and hallucinate is.</li><li>Monitor chat sessions. This will give you an indication of topics that could use improvement or new knowledge bits to include in the future.</li><li>Use the long context that your LLM provides for key information (e.g. customer service phone number). This is information that should accompany every query and you definitely don’t want to get wrong. Popular company acronyms should go here too.</li><li>Deduplicate aggressively. Look for key terms and tools and make sure they are introduced exactly once. Others should reference them.</li><li>Use powerful markdown tools that offer backlinks and documentation linking (e.g. Obsidian) to monitor duplication and coverage of your knowledge base.</li><li>For each document, use an LLM to create a brief executive summary. If the summary doesn’t capture the knowledge correctly, chances are that the RAG will fail to interpret correctly too, so you’ll need to revise the clarity of your doc. Include the final executive summary at the top of each document.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=913452fb71b8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dsaid-govtech/the-bots-are-here-now-what-how-knowledge-management-became-the-key-to-powering-genai-solutions-913452fb71b8">“The Bots Are Here. Now What?” 
How Knowledge Management Became the Key to Powering GenAI Solutions</a> was originally published in <a href="https://medium.com/dsaid-govtech">AI Practice and Data Engineering Practice, GovTech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tell me who you hang out and I’ll tell you who you are : K-Nearest Neighbors]]></title>
            <link>https://medium.com/@AleAlejandro1/tell-me-who-you-hang-out-and-ill-tell-you-who-you-are-k-nearest-neighbors-b28e24f74bd9?source=rss-685474db29ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/b28e24f74bd9</guid>
            <category><![CDATA[knn-classification]]></category>
            <category><![CDATA[knn]]></category>
            <category><![CDATA[classification-algorithms]]></category>
            <category><![CDATA[bias-in-ai]]></category>
            <category><![CDATA[stereotypes]]></category>
            <dc:creator><![CDATA[AleAlejandro1]]></dc:creator>
            <pubDate>Fri, 29 Oct 2021 06:27:23 GMT</pubDate>
            <atom:updated>2021-10-29T06:27:23.723Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tell me who you hang out and I’ll tell you who you are : K-Nearest Neighbors</h3><p>K-Nearest Neighbors (KNN) is one of those examples of how stereotypes tend to be true, but not always. If you think about what the algorithm does, is essentially:</p><ol><li>Establish a way to measure distance, this means a distance in the feature space. Two points in space are separated by a distance. There are many ways to measure distances.</li><li>Define how many neighbors we’ll be surveying. We’ll start with the nearest ones.</li><li>Ask the neighbors of the point in question and aggregate their answers (majority or average).</li><li>The end</li></ol><p>Let’s take for example we are in trying to predict if someone is likely to become pregnant within the next 6 months. We have access to features like “age”, “income”, “housing fees”. And we have a bunch of rows of data, where we also have the answer (“got pregnant within 6 months”/”didn’t get pregnant within 6 months”).</p><p>Be placing a new point in this feature space, we can just look the data points around it and see what’s the most popular answer. In this way, we can classify the new data point, predicting based on what others near in the feature space have done before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jr-eifoTu6GNVmaT7DHlvA.png" /><figcaption>We want to predict if the test point (?) will get pregnant within the next 6 months. Within the circle, we see it’s 4 nearest neighbors. Three belong to class A and one belongs to class B. If we use the KNN algorithm with k=4, our test point will be categorized as class A.</figcaption></figure><blockquote>Something to keep in mind: This algorithm makes it easy to appreciate how it is easy to stereotype and label an unknown based on existing adjacent but independent data.</blockquote><p>So how can we use this machine for generalising things we don’t know? It’s readily available in sklearn, you can see an example with random data below.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dimport%252520pandas%252520as%252520pd%25250Aimport%252520seaborn%252520as%252520sns%25250Afrom%252520sklearn.datasets%252520import%252520make_classification%252520%252523%252523%252520This%252520we%252520can%252520use%252520to%252520generate%252520fake%252520data%25250A%25250A%252523%252523%252520Generate%252520a%252520random%252520dataset%252520with%2525202%252520features%252520and%252520a%252520target%252520with%2525202%252520classes%25250Adata%252520%25253D%252520make_classification%2528n_samples%25253D1000%25252Cn_informative%25253D2%25252C%252520n_redundant%25253D0%25252C%252520n_repeated%25253D0%25252C%25250A%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520n_clusters_per_class%25253D2%25252Cn_features%25253D2%25252C%2529%25250Adf%252520%25253D%252520pd.DataFrame%2528data%25255B0%25255D%25252C%252520columns%25253D%25255B%2527feature%252520A%2527%25252C%2527feature%252520B%2527%25255D%2529%25250Adf%25255B%2527target%2527%25255D%25253Ddata%25255B1%25255D&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dimport%25252520pandas%25252520as%25252520pd%2525250Aimport%25252520seaborn%25252520as%25252520sns%2525250Afrom%25252520sklearn.datasets%25252520import%25252520make_classification%25252520%25252523%25252523%25252520This%25252520we%25252520can%25252520use%25252520to%25252520generate%25252520fake%25252520data%2525250A%2525250A%25252523%25252523%25252520Generate%25252520a%25252520random%25252520dataset%25252520with%252525202%25252520features%25252520and%25252520a%25252520target%25252520with%252525202%25252520classes%2525250Adata%25252520%2525253D%25252520make_classification%252528n_samples%2525253D1000%2525252Cn_informative%2525253D2%2525252C%25252520n_redundant%2525253D0%2525252C%25252520n_repeated%2525253D0%2525252C%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520n_clusters_per_class%2525253D2%2525252Cn_features%2525253D2%2525252C%252529%2525250Adf%25252520%2525253D%25252520pd.DataFrame%252528data%2525255B0%2525255D%2525252C%25252520columns%2525253D%2525255B%252527feature%25252520A%252527%2525252C%252527feature%25252520B%252527%2525255D%252529%2525250Adf%2525255B%252527target%252527%2525255D%2525253Ddata%2525255B1%2525255D&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/61af5915d3d399958e57bf4892424a21/href">https://medium.com/media/61af5915d3d399958e57bf4892424a21/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*OImLhOS39ZkD8eaZyT8htw.png" /><figcaption>Randomly generate data for classification. Feature A and Feature B are used to classify the target (class 0 or class 1). We’ll use KNNClassifier on this.</figcaption></figure><p>Now that we have a dataset, we can evaluate how well the model scores. We will split the data into train and test. This is because we are interested in the model performing well on never seen before data. You’ll see that if not handled, this can be problematic for KNN.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dfrom%252520sklearn.neighbors%252520import%252520KNeighborsClassifier%252520%252523%252523%252520this%252520is%252520the%252520machine%252520learning%252520model%25250Afrom%252520sklearn.model_selection%252520import%252520train_test_split%25250AX_train%25252C%252520X_test%25252C%252520y_train%25252C%252520y_test%252520%25253D%252520train_test_split%2528df.drop%2528columns%25253D%25255B%2527target%2527%25255D%2529%25252Cdf%25255B%2527target%2527%25255D%2529%25250A%25250Amodel%252520%25253D%252520KNeighborsClassifier%2528n_neighbors%25253D2%2529%25250Amodel.fit%2528X_train%25252Cy_train%2529%25250A%25250Amodel.score%2528X_train%25252Cy_train%2529%25250A%252523%252523%252520Answer%252520is%252520%25253A%2525200.9466666666666667%25250A%25250Amodel.score%2528X_test%25252Cy_test%2529%25250A%252523%252520Answer%252520is%252520%25253A%2525200.8&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dfrom%25252520sklearn.neighbors%25252520import%25252520KNeighborsClassifier%25252520%25252523%25252523%25252520this%25252520is%25252520the%25252520machine%25252520learning%25252520model%2525250Afrom%25252520sklearn.model_selection%25252520import%25252520train_test_split%2525250AX_train%2525252C%25252520X_test%2525252C%25252520y_train%2525252C%25252520y_test%25252520%2525253D%25252520train_test_split%252528df.drop%252528columns%2525253D%2525255B%252527target%252527%2525255D%252529%2525252Cdf%2525255B%252527target%252527%2525255D%252529%2525250A%2525250Amodel%25252520%2525253D%25252520KNeighborsClassifier%252528n_neighbors%2525253D2%252529%2525250Amodel.fit%252528X_train%2525252Cy_train%252529%2525250A%2525250Amodel.score%252528X_train%2525252Cy_train%252529%2525250A%25252523%25252523%25252520Answer%25252520is%25252520%2525253A%252525200.9466666666666667%2525250A%2525250Amodel.score%252528X_test%2525252Cy_test%252529%2525250A%25252523%25252520Answer%25252520is%25252520%2525253A%252525200.8&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6fa64fcf6b57db3999cbae2b0f983e7f/href">https://medium.com/media/6fa64fcf6b57db3999cbae2b0f983e7f/href</a></iframe><p>KNN has a very important hyperparameter. It’s so important that is part of the name. I am referring to the amount of neighbors to be considered, designated as <strong>K</strong>. For a quick interpretation, picture the following two scenarios:</p><p>a) We ask a colleague who works closely with you, to describe yourself. Some things this person might know very well, others ignore totally.</p><p>b) We ask a colleague, your parents, your friends, your neighbors and some strangers about you. We consider everything they say and take the points that are most popular.</p><p>Likely, scenario b) is a more averaged representation of you, whereas a) can be totally sharp or totally wrong. We can investigate this numerically, by analysing the learning curves (for train and test data) as a function of <strong>K</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*TVsFF34lDklQb8SzlMionw.png" /><figcaption>We can see that the selection of amount of neighbors (K) has a clear impact on the performance of the model. How to choose K? it depends</figcaption></figure><p>Chances are there is no universally correct K, you’ll have to try. The following interpretation still holds true:</p><blockquote>A “small” K will provide a lot of overfit, whereas a “large” K will provide a lot of bias. The more people we ask, the more the answer remains the same. If we ask only one person, the answer is totally sensitive to what they say.</blockquote><p>If we wouldn’t have done the train test split, we would have missed this, as the model with small K has extremely high score. But we are interested in predicting unknowns, so whatever happens on the train set… is not always so indicative.</p><p>Until next time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b28e24f74bd9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning when you are not popular: The problem with class imbalance]]></title>
            <link>https://medium.com/@AleAlejandro1/machine-learning-when-you-are-not-popular-the-problem-with-class-imbalance-485da397f1ac?source=rss-685474db29ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/485da397f1ac</guid>
            <category><![CDATA[imbalanced-data]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[sampling]]></category>
            <category><![CDATA[underrepresented]]></category>
            <category><![CDATA[sklearn]]></category>
            <dc:creator><![CDATA[AleAlejandro1]]></dc:creator>
            <pubDate>Thu, 14 Oct 2021 02:45:37 GMT</pubDate>
            <atom:updated>2021-10-14T02:45:37.697Z</atom:updated>
            <content:encoded><![CDATA[<p>Supervised learning methods like Logistic Regression are very good at learning what’s on the data and repeating the pattern. This makes job of whoever is obtaining the data all the more harder, when there might be any form of uneven distribution of class. I’m going to give an example showing how certain metrics can be deceiving and what you should look out for.</p><p>Let’s say I have a certain population, which has a continuous feature and a target class that can take value 0 and 1. Let’s say that class 1 is very popular, so that 90% of all population is class 1. Let me generate that and show you how it looks like:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dpopulation%252520%25253D%2525201000%25250Aclass_split%252520%25253D%2525200.9%25250Aclass_1_size%252520%25253D%252520round%2528class_split%252520%252A%2525201000%2529%25250Aclass_2_size%252520%25253D%252520population%252520-%252520class_1_size%25250Adict_1%252520%25253D%252520%25257B%2527feature%2527%25253A%25255Brandom.random%2528%2529%252520for%252520_%252520in%252520range%2528class_1_size%2529%25255D%25252C%2527target%2527%25253A%252520%25255B1%252520for%252520_%252520in%252520range%2528class_1_size%2529%25255D%25257D%25250Adict_0%252520%25253D%252520%25257B%2527feature%2527%25253A%25255B0.7%25252Brandom.random%2528%2529%252520for%252520_%252520in%252520range%2528class_2_size%2529%25255D%25252C%2527target%2527%25253A%252520%25255B0%252520for%252520_%252520in%252520range%2528class_2_size%2529%25255D%25257D%25250A%25250Adf%252520%25253Dpd.concat%2528%25255Bpd.DataFrame.from_dict%2528dict_0%2529%25252Cpd.DataFrame.from_dict%2528%25250A%252520%252520dict_1%2529%25255D%25252Caxis%25253D0%2529.reset_index%2528%2529.drop%2528columns%25253D%25255B%2527index%2527%25255D%2529%25250Adf.head%2528%2529&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dpopulation%25252520%2525253D%252525201000%2525250Aclass_split%25252520%2525253D%252525200.9%2525250Aclass_1_size%25252520%2525253D%25252520round%252528class_split%25252520%25252A%252525201000%252529%2525250Aclass_2_size%25252520%2525253D%25252520population%25252520-%25252520class_1_size%2525250Adict_1%25252520%2525253D%25252520%2525257B%252527feature%252527%2525253A%2525255Brandom.random%252528%252529%25252520for%25252520_%25252520in%25252520range%252528class_1_size%252529%2525255D%2525252C%252527target%252527%2525253A%25252520%2525255B1%25252520for%25252520_%25252520in%25252520range%252528class_1_size%252529%2525255D%2525257D%2525250Adict_0%25252520%2525253D%25252520%2525257B%252527feature%252527%2525253A%2525255B0.7%2525252Brandom.random%252528%252529%25252520for%25252520_%25252520in%25252520range%252528class_2_size%252529%2525255D%2525252C%252527target%252527%2525253A%25252520%2525255B0%25252520for%25252520_%25252520in%25252520range%252528class_2_size%252529%2525255D%2525257D%2525250A%2525250Adf%25252520%2525253Dpd.concat%252528%2525255Bpd.DataFrame.from_dict%252528dict_0%252529%2525252Cpd.DataFrame.from_dict%252528%2525250A%25252520%25252520dict_1%252529%2525255D%2525252Caxis%2525253D0%252529.reset_index%252528%252529.drop%252528columns%2525253D%2525255B%252527index%252527%2525255D%252529%2525250Adf.head%252528%252529&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e03c9f4e0e4481914de8700262eefe8c/href">https://medium.com/media/e03c9f4e0e4481914de8700262eefe8c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*wHXjZUBkuH3RU9MHIfh4ww.png" /><figcaption>A fictitious population where 90% is class 1 and 10% is class 0, for a certain continuous feature. Feature seems to be a good indicator to predict target.</figcaption></figure><p>So now, let’s assume that we are only able to sample a sub-set of the whole population. We can take random (arbitrary) n=200 data points and use that to train a machine learning model. In particular, we can use sklearn to do a LogisticRegression model, train it and when we check for the metrics, we get precision, accuracy and recall &gt; 0.9. We all pat each other’s backs and go for a drink to celebrate.</p><p>Now, we can try an experiment. Let’s say that we come up with another type of predictor. One that ALWAYS returns the majority class, how would that perform? Let’s compare with the Logistic Regression:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dfrom%252520sklearn.linear_model%252520import%252520LogisticRegression%25250Afrom%252520sklearn.model_selection%252520import%252520train_test_split%25250Afrom%252520sklearn.metrics%252520import%252520precision_score%25252C%252520accuracy_score%25252C%252520recall_score%25250A%25250Asample_df%252520%25253D%252520df.sample%2528n%25253D200%25252Crandom_state%25253D159%2529%25250AX_train%25252C%252520X_test%25252C%252520y_train%25252C%252520y_test%252520%25253D%252520train_test_split%2528sample_df%25255B%25255B%2527feature%2527%25255D%25255D%25252Csample_df%25255B%2527target%2527%25255D%25252Ctest_size%25253D0.3%2529%25250A%25250Alogistic_model%252520%25253D%252520LogisticRegression%2528%2529.fit%2528X_train%25252Cy_train%2529%25250Ay_log_pred%252520%25253D%252520logistic_model.predict%2528X_test%2529%252520%252523%252520Use%252520logistic%252520regression%252520to%252520predict%25250Ay_maj_pred%252520%25253D%252520np.ones_like%2528X_test%2529%252520%252523%252520Predict%252520by%252520returning%252520always%252520class%2525201%25250A%25250Aprint%2528f%2527precision%25253A%252520majority%252520%25253D%252520%25257Bprecision_score%2528y_test%25252Cy_maj_pred%2529%25257D%252520logistic%252520%25257Bprecision_score%2528y_test%25252Cy_log_pred%2529%25257D%2527%2529%25250Aprint%2528f%2527accuracy%25253A%252520majority%252520%25257Baccuracy_score%2528y_test%25252Cy_maj_pred%2529%25257D%252520logistic%252520%25257Baccuracy_score%2528y_test%25252Cy_log_pred%2529%25257D%2527%2529%25250Aprint%2528%2527recall%2527%25252Crecall_score%2528y_test%25252Cy_maj_pred%2529%25252Crecall_score%2528y_test%25252Cy_log_pred%2529%2529%25250A%25250A%252523%252520precision%25253A%252520majority%252520%25253D%2525200.9333333333333333%252520logistic%2525200.9655172413793104%25250A%252523%252520accuracy%2525200.9333333333333333%2525200.9666666666666667%25250A%252523%252520recall%2525201.0%2525201.0&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dfrom%25252520sklearn.linear_model%25252520import%25252520LogisticRegression%2525250Afrom%25252520sklearn.model_selection%25252520import%25252520train_test_split%2525250Afrom%25252520sklearn.metrics%25252520import%25252520precision_score%2525252C%25252520accuracy_score%2525252C%25252520recall_score%2525250A%2525250Asample_df%25252520%2525253D%25252520df.sample%252528n%2525253D200%2525252Crandom_state%2525253D159%252529%2525250AX_train%2525252C%25252520X_test%2525252C%25252520y_train%2525252C%25252520y_test%25252520%2525253D%25252520train_test_split%252528sample_df%2525255B%2525255B%252527feature%252527%2525255D%2525255D%2525252Csample_df%2525255B%252527target%252527%2525255D%2525252Ctest_size%2525253D0.3%252529%2525250A%2525250Alogistic_model%25252520%2525253D%25252520LogisticRegression%252528%252529.fit%252528X_train%2525252Cy_train%252529%2525250Ay_log_pred%25252520%2525253D%25252520logistic_model.predict%252528X_test%252529%25252520%25252523%25252520Use%25252520logistic%25252520regression%25252520to%25252520predict%2525250Ay_maj_pred%25252520%2525253D%25252520np.ones_like%252528X_test%252529%25252520%25252523%25252520Predict%25252520by%25252520returning%25252520always%25252520class%252525201%2525250A%2525250Aprint%252528f%252527precision%2525253A%25252520majority%25252520%2525253D%25252520%2525257Bprecision_score%252528y_test%2525252Cy_maj_pred%252529%2525257D%25252520logistic%25252520%2525257Bprecision_score%252528y_test%2525252Cy_log_pred%252529%2525257D%252527%252529%2525250Aprint%252528f%252527accuracy%2525253A%25252520majority%25252520%2525257Baccuracy_score%252528y_test%2525252Cy_maj_pred%252529%2525257D%25252520logistic%25252520%2525257Baccuracy_score%252528y_test%2525252Cy_log_pred%252529%2525257D%252527%252529%2525250Aprint%252528%252527recall%252527%2525252Crecall_score%252528y_test%2525252Cy_maj_pred%252529%2525252Crecall_score%252528y_test%2525252Cy_log_pred%252529%252529%2525250A%2525250A%25252523%25252520precision%2525253A%25252520majority%25252520%2525253D%252525200.9333333333333333%25252520logistic%252525200.9655172413793104%2525250A%25252523%25252520accuracy%252525200.9333333333333333%252525200.9666666666666667%2525250A%25252523%25252520recall%252525201.0%252525201.0&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce44a57692dceb558142e64c71bae436/href">https://medium.com/media/ce44a57692dceb558142e64c71bae436/href</a></iframe><p>Now this is interesting. The Logistic Regression is slightly better, but the scary part here is that we are also getting really good metric score by just returning the default value of the popular class. This is bad if you are trying to predict anything for the minority class. In fact, let’s take a bunch of data that ONLY contains the minority class and see how both our models perform there.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Ddf_class2%252520%25253D%252520pd.DataFrame.from_dict%2528dict_0%2529%25250A%25250AX_train%25252C%252520X_test%25252C%252520y_train%25252C%252520y_test%252520%25253D%252520train_test_split%2528df_class2%25255B%25255B%2527feature%2527%25255D%25255D%25252Cdf_class2%25255B%2527target%2527%25255D%25252Ctest_size%25253D0.3%2529%25250A%25250A%25250Ay_log_pred%252520%25253D%252520logistic_model.predict%2528X_test%2529%25250Ay_maj_pred%252520%25253D%252520np.ones_like%2528X_test%2529%25250A%25250Aprint%2528f%2527precision%25253A%252520majority%252520%25257Bprecision_score%2528y_test%25252Cy_maj_pred%2529%25257D%252520logistic%252520%25257Bprecision_score%2528y_test%25252Cy_log_pred%2529%25257D%2527%2529%25250Aprint%2528f%2527accuracy%25253A%252520majority%252520%25257Baccuracy_score%2528y_test%25252Cy_maj_pred%2529%25257D%252520logistic%252520%25257Baccuracy_score%2528y_test%25252Cy_log_pred%2529%25257D%2527%2529%25250Aprint%2528%2527recall%2527%25252Crecall_score%2528y_test%25252Cy_maj_pred%2529%25252Crecall_score%2528y_test%25252Cy_log_pred%2529%2529%25250A%25250A%252523%252520precision%25253A%252520majority%2525200.0%252520logistic%2525200.0%25250A%252523%252520accuracy%25253A%252520majority%2525200.0%252520logistic%2525200.2%25250A%252523%252520recall%2525200.0%2525200.0&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Ddf_class2%25252520%2525253D%25252520pd.DataFrame.from_dict%252528dict_0%252529%2525250A%2525250AX_train%2525252C%25252520X_test%2525252C%25252520y_train%2525252C%25252520y_test%25252520%2525253D%25252520train_test_split%252528df_class2%2525255B%2525255B%252527feature%252527%2525255D%2525255D%2525252Cdf_class2%2525255B%252527target%252527%2525255D%2525252Ctest_size%2525253D0.3%252529%2525250A%2525250A%2525250Ay_log_pred%25252520%2525253D%25252520logistic_model.predict%252528X_test%252529%2525250Ay_maj_pred%25252520%2525253D%25252520np.ones_like%252528X_test%252529%2525250A%2525250Aprint%252528f%252527precision%2525253A%25252520majority%25252520%2525257Bprecision_score%252528y_test%2525252Cy_maj_pred%252529%2525257D%25252520logistic%25252520%2525257Bprecision_score%252528y_test%2525252Cy_log_pred%252529%2525257D%252527%252529%2525250Aprint%252528f%252527accuracy%2525253A%25252520majority%25252520%2525257Baccuracy_score%252528y_test%2525252Cy_maj_pred%252529%2525257D%25252520logistic%25252520%2525257Baccuracy_score%252528y_test%2525252Cy_log_pred%252529%2525257D%252527%252529%2525250Aprint%252528%252527recall%252527%2525252Crecall_score%252528y_test%2525252Cy_maj_pred%252529%2525252Crecall_score%252528y_test%2525252Cy_log_pred%252529%252529%2525250A%2525250A%25252523%25252520precision%2525253A%25252520majority%252525200.0%25252520logistic%252525200.0%2525250A%25252523%25252520accuracy%2525253A%25252520majority%252525200.0%25252520logistic%252525200.2%2525250A%25252523%25252520recall%252525200.0%252525200.0&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a15f167c722f28b124aeb4d1680746f/href">https://medium.com/media/5a15f167c722f28b124aeb4d1680746f/href</a></iframe><p>Total garbage. It was expected that always returning the majority class will perform like this. But, the Logistic Regression and all the metrics would have told you that you were doing a great job. <strong>Check the dataset before you start with the machine learning model and prediction</strong>.</p><p>So what to do? This population is about 90/10 split, which is highly imbalanced. The sample we are taking can be even worse than that! So first-off, if you check for the target class split and is more uneven than 70/30, whatever you get will be treating the underrepresented class poorly.</p><p>There are some artificial steps you can take, such as <strong>duplicating data</strong> for the class that is underrepresented. You could also <strong>remove data</strong> from the majority class. These artificial steps, make sure your algorithm puts in similar weights both classes, but nothing is free. Less data is typically bad. Duplicating data? I thought we always should avoid that. Will try to get to write about this sometime soon. Until next time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=485da397f1ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When your target is a category, your ‘regression’ is not a regression]]></title>
            <link>https://medium.com/@AleAlejandro1/when-your-target-is-a-category-your-regression-is-not-a-regression-3b6d9a531d7d?source=rss-685474db29ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b6d9a531d7d</guid>
            <category><![CDATA[maximum-likelihood]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[r-squared]]></category>
            <category><![CDATA[categorical-data]]></category>
            <dc:creator><![CDATA[AleAlejandro1]]></dc:creator>
            <pubDate>Thu, 07 Oct 2021 10:55:51 GMT</pubDate>
            <atom:updated>2021-10-07T10:55:51.424Z</atom:updated>
            <content:encoded><![CDATA[<p>There is a lot of understanding for the ordinary least square method to find a line (intersect and slope) that can fit some data points as best as possible, and many ways to quantify how good this fit is. And most of it is over 200 years old.</p><p>Turns out most of the world is not linear and even though most approximations are linear, because solving things mathematically exactly is hard/impossible otherwise, sometimes is simply categorically wrong to use linear approaches.</p><p>Take for example you are trying to predict a binary outcome: “Given the weather conditions, will it rain today?” Answer is a yes or no (called Bernoulli event). However, you might have many continuous variables such as humidity, pressure and temperature that vary over wide ranges. Imagine we are trying to predict rain based on humidity. Based on many observations we might have found data that indicates the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*w5URSpTK0eF94xjDkcnl8g.png" /><figcaption>A very bad model to predict the weather (0 = no rain, 1 = rain) using humidity. Main point is that for a continuous variable X (feature = humidity) the Y coordinate only can take 2 possible values. This data is made up.</figcaption></figure><p>So can we apply linear regression to get a line to represent this? Definitely not. Unless we take a horizontal line (no slope, only intercept), our line will take values that are not permitted, such as &lt;0 or &gt;1. However, all the things we had (such as R² and cool methods to determine the line) were so good. Can we re-use them, at least partially?</p><p>Well.. yes, but wait. First off, we will need a function to model the data points that we have. For this, we can consider a sigmoid function. This function is quite popular because you can input values that range from -\infinity to \infinity and it will return values between 0 and 1. The sigmoid is NOT the same as a boolean signal, it doesn’t even <em>touch</em> the 1 and 0 dotted line, but is good enough to produce a good approximation. Maybe not near the jump though. See below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*0tIY5XWGuoXjGHwkks064A.png" /><figcaption>The Sigmoid function is pretty close to our data. By rounding to the closest extreme (0 or 1) we can use the sigmoid to predict Weather based on Humidity. What happens close to the jump? the model is quite hypersensitive there. Note this sigmoid i drew by inputting the formula by hand, not by fitting.</figcaption></figure><p>Ok, so it looks like if we can find the parameters of such a sigmoid, we have a good representation for the data and we can use that to make predictions. So how do we find the exact parameters of the sigmoid curve? It would be cool if we could fit it using something like least squares.</p><blockquote>If you want a quick answer : to solve this, you are looking for what’s called a <em>logistic regression</em>, involving a <em>logit</em> link function.</blockquote><p>If we were to do a deeper dive on the math involved here, we would need to touch on the topic of generalised linear models, which aim to provide a common approach to many types of regressions. If you want to learn more about them, check out this video:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FJ4zNmGqttVo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DJ4zNmGqttVo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FJ4zNmGqttVo%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf594eacd431e74af5d927d8791aed0a/href">https://medium.com/media/cf594eacd431e74af5d927d8791aed0a/href</a></iframe><p>Coming back to the weather. To get the actual sigmoid that best fits this situation, we will just fit one using statsmodels (sklearn works too). Statsmodels will provide a more rich summary (see below).</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dimport%252520statsmodels.formula.api%252520as%252520smf%25250Amodel%252520%25253D%252520smf.logit%2528formula%25253D%2527target%252520%257E%252520feature%2527%25252C%252520data%25253Ddf%2529.fit%2528%2529%25253B%25250A%25250Aplt.figure%2528figsize%25253D%252816%25252C6%2529%2529%25250Aplt.hlines%25281%25252C0%25252C100%25252Clinestyles%25253D%2527dashed%2527%25252Ccolor%25253D%2527k%2527%25252Calpha%25253D0.3%2529%25250Aplt.hlines%25280%25252C0%25252C100%25252Clinestyles%25253D%2527dashed%2527%25252Ccolor%25253D%2527k%2527%25252Calpha%25253D0.3%2529%25250Asns.lineplot%2528x%25253Dx%25252Cy%25253D1%25252F%25281%25252Bnp.exp%2528-%2528x-50%2529%2529%2529%25252Ccolor%25253D%2527k%2527%25252Clabel%25253D%2527sigmoid%2527%25252Cdashes%25253DTrue%25252C%252520lw%25253D1.5%2529%25250Asns.lineplot%2528df%25255B%2527feature%2527%25255D%25252Cmodel.predict%2528df%25255B%2527feature%2527%25255D%2529%25252Ccolor%25253D%2527r%2527%25252Clabel%25253D%2527logit%252520fit%2527%25252Clw%25253D5%2529%25250Asns.scatterplot%2528x%25253Dx%25252Cy%25253Dy%25252Cpalette%25253D%2527blue%2527%25252Calpha%25253D0.7%25252C%252520label%25253D%2527data%2527%25252Cs%25253D100%2529%25250A%25250Aplt.xlabel%2528%2527Humidity%252520%25255Bg%25252Fkg%25255D%2527%25252C%252520fontsize%25253D18%2529%25250Aplt.ylabel%2528%2527Weather%2527%25252C%252520fontsize%25253D18%2529%25250Aplt.plot%2528%2529&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dimport%25252520statsmodels.formula.api%25252520as%25252520smf%2525250Amodel%25252520%2525253D%25252520smf.logit%252528formula%2525253D%252527target%25252520%25257E%25252520feature%252527%2525252C%25252520data%2525253Ddf%252529.fit%252528%252529%2525253B%2525250A%2525250Aplt.figure%252528figsize%2525253D%25252816%2525252C6%252529%252529%2525250Aplt.hlines%2525281%2525252C0%2525252C100%2525252Clinestyles%2525253D%252527dashed%252527%2525252Ccolor%2525253D%252527k%252527%2525252Calpha%2525253D0.3%252529%2525250Aplt.hlines%2525280%2525252C0%2525252C100%2525252Clinestyles%2525253D%252527dashed%252527%2525252Ccolor%2525253D%252527k%252527%2525252Calpha%2525253D0.3%252529%2525250Asns.lineplot%252528x%2525253Dx%2525252Cy%2525253D1%2525252F%2525281%2525252Bnp.exp%252528-%252528x-50%252529%252529%252529%2525252Ccolor%2525253D%252527k%252527%2525252Clabel%2525253D%252527sigmoid%252527%2525252Cdashes%2525253DTrue%2525252C%25252520lw%2525253D1.5%252529%2525250Asns.lineplot%252528df%2525255B%252527feature%252527%2525255D%2525252Cmodel.predict%252528df%2525255B%252527feature%252527%2525255D%252529%2525252Ccolor%2525253D%252527r%252527%2525252Clabel%2525253D%252527logit%25252520fit%252527%2525252Clw%2525253D5%252529%2525250Asns.scatterplot%252528x%2525253Dx%2525252Cy%2525253Dy%2525252Cpalette%2525253D%252527blue%252527%2525252Calpha%2525253D0.7%2525252C%25252520label%2525253D%252527data%252527%2525252Cs%2525253D100%252529%2525250A%2525250Aplt.xlabel%252528%252527Humidity%25252520%2525255Bg%2525252Fkg%2525255D%252527%2525252C%25252520fontsize%2525253D18%252529%2525250Aplt.ylabel%252528%252527Weather%252527%2525252C%25252520fontsize%2525253D18%252529%2525250Aplt.plot%252528%252529&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/141d513978e6c2ae2e5ddad133115795/href">https://medium.com/media/141d513978e6c2ae2e5ddad133115795/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*-lDWzgetaJAgjz-EShMWyA.png" /><figcaption>Here we see the data points, the manual fit of the sigmoid and the curve I get from the statsmodels.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*RyOJbzN4X0VXmqcaXoYxXA.png" /><figcaption>Checkout all the cool parameters statsmodels gives us for this fit.</figcaption></figure><p>This fit looks good as a model of reality, however there are a few important clarifications to be made here:</p><ul><li>Sigmoids have a jump, near the jump the curve is hypersensitive. Maybe don’t trust the outcome near the jump.</li><li>Sigmoids ‘never’ touch 0 and 1. But we are trying to predict 0’s and 1’s. The sigmoid then is a probability of getting category 1 or category 2.</li><li>The actual prediction of the model is categorical, but the fitted curve returns a number 0 &lt; p(X) &lt; 1 that depending on the feature X, will tell us the probability of getting a category.</li><li>Regression yields values in a continuum in the target space, this ‘regression’ yields categorical data. This is not a regression.</li><li>Since the logistic curve yields a probability, the way it finds the best parameters, is by maximizing likelihood of getting the data with this curve. That’s why the method called is Maximum Likelihood Estimator (MLE)</li><li>Pseudo R²: Statsmodels calculates an R² comparing the MLE for the mean value of the target with the MLE we get for our fit. Pseudo R² also goes [0–1] and the closer to 1 the better, but not as good a predictor as the linear R². Good to compare different logistic regressions for the same data though!</li></ul><p>Until next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b6d9a531d7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coefficient of Determination : negative R-squared and residuals]]></title>
            <link>https://medium.com/@AleAlejandro1/coefficient-of-determination-negative-r-squared-and-residuals-f2295fd94a89?source=rss-685474db29ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2295fd94a89</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[residual]]></category>
            <category><![CDATA[linear-regression-python]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[r-squared]]></category>
            <dc:creator><![CDATA[AleAlejandro1]]></dc:creator>
            <pubDate>Mon, 27 Sep 2021 16:46:09 GMT</pubDate>
            <atom:updated>2021-10-05T09:15:43.006Z</atom:updated>
            <content:encoded><![CDATA[<h3>Coefficient of Determination : negative R-squared and residuals</h3><blockquote>All models are wrong, but some are useful.</blockquote><p>Famously said by George Box, when doing statistics, we will take whatever data we have to try to come up with a model of reality. When investigating relationship between variables that seem to be correlated, is a common approach to try to find a line (in one or many dimensions) that fits the data points well.</p><p>Note that the reverse of this is very bad behaviour unless you can explain it. Modifying the data to fit a line should be consider when you are very certain you are in the presence of an error of measurement or some sort of outlier that does not represent the population you are trying to investigate. Then you can remove it.</p><p>Anyway, you will probably be using a linear regression method to calculate the parameters of the line equation (slope and intercept). Most famous one is the ordinary linear regression, which measures the square of the distance between the proposed line and the actual data points is trying to catch. Note it is the square of the difference, not the module of the difference nor just the difference. This will be important later.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%252523import%252520stuff%25250Aimport%252520statsmodels.formula.api%252520as%252520smf%25250A%25250A%252523model%252520instancing%25250Amodel%252520%25253D%252520smf.ols%2528formula%25253D%2527target%252520%257E%252520variable_1%2527%25252C%252520data%25253Dmy_dataset%2529%25250A%25250A%252523train%252520the%252520model%25250Amodel%252520%25253D%252520model.fit%2528%2529%25250A%25250A%252523ready%252520to%252520predict%25253A%252520Give%252520me%252520X%252520i%252520give%252520you%252520model%2528X%2529.&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%25252523import%25252520stuff%2525250Aimport%25252520statsmodels.formula.api%25252520as%25252520smf%2525250A%2525250A%25252523model%25252520instancing%2525250Amodel%25252520%2525253D%25252520smf.ols%252528formula%2525253D%252527target%25252520%25257E%25252520variable_1%252527%2525252C%25252520data%2525253Dmy_dataset%252529%2525250A%2525250A%25252523train%25252520the%25252520model%2525250Amodel%25252520%2525253D%25252520model.fit%252528%252529%2525250A%2525250A%25252523ready%25252520to%25252520predict%2525253A%25252520Give%25252520me%25252520X%25252520i%25252520give%25252520you%25252520model%252528X%252529.&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f22ca984c8d86a0ecd90d996b508c990/href">https://medium.com/media/f22ca984c8d86a0ecd90d996b508c990/href</a></iframe><p>When you fit this line, your fit might or might not be good. If the relationship between the 2 variables is linear, then you are probably going to obtain a good fit and your model will be very accurate in representing reality. What is good fit?</p><p>One way is to look at how bad we did when predicting with the model (y_predicted) vs reality (y_measured). If we take the difference between y_predicted and y_measured we can compute what’s called the residual. Looking at how those distribute, might give us an indication of how good our fit is. Residuals that have an asymmetrical distribution is typically bad news, unless you are trying to overcompensate or under-compensate on purpose (e.g. your model should be above the data points because if it goes below someone dies).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*U2FscInuJbHCORuHPyeRoQ.png" /><figcaption>Asymmetrical distribution of residuals is typically a red flag for the fit quality. This histogram of residuals looks pretty symmetrical.</figcaption></figure><p>Another way, is to look at the Coefficient of Determination, or how everyone calls it, the “R-Squared”. In school, we were all told this one must be close to 1 if the model represents the data well. How is it calculated?</p><p>There are few definitions to calculate R-Squared. In the context of data analysis in Python, one of the easier ways can be to take the residuals (the ones we defined above) and the variance of the target variables (\sigma²) as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*t5ORUq0pTqP6Es7i5Rh3-g.png" /><figcaption>The ratio between the sum of residuals squared and the variance, tells us how good the fit is. I write the equation in this way to highlight the ‘data sampling’ aspects (denominator) and the model fit aspects (numerator)</figcaption></figure><p>So, this formula of R-squared, is essentially a comparison between the variance of the measured data and the residuals of our models, both are squared. We can then see how the denominator and numerator contribute to the end result of R².</p><p>On the numerator, note here that big residuals, even if they are symmetrically distributed around, imply big numerator -&gt; means R² not so close 1. This means our line doesn’t ‘touch’ so many points. Residuals is about your model and how it represents the measured data.</p><p>In the denominator, $n$ represents the amount of data in our sample, but it is the variance the most important aspect. From the denominator in the equation above we can see that a dataset with a huge variance, will contribute to having an R² closer to 1. On the other hand, datasets where most points are close to the mean (i.e. the mean is a good model of the dataset), will have very low variance and will contribute to have a <em>further from 1</em> value of R². Here we are seeing only the effects of a large or small denominator. Note that your model is not represented in the denominator.</p><p>Now picture this scenario. We choose a linear model with intercept = 0, but reality is that the data is is represented well by a constant and a slope (both non-zero) as shown in the figure below. In that case, because we are forcing an intercept = 0 model, our residuals are going to be pretty big (bad) as we move away from the origin. Also, because the data is mostly constant, the mean represents it very well, so the variance is low. This is a situation where R² can be negative.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6LRaunTD1aglhnRZM96d2w.png" /><figcaption>If we force our linear model to go through the origin, we might encounter a negative R². See how the residuals (vertical lines) grow linearly on average.</figcaption></figure><p>There are other examples where R² is not what we expect (see wikipedia for everything <a href="https://en.wikipedia.org/wiki/Coefficient_of_determination">LINK</a>). The main point I wanted to communicate is that just looking at R² is helpful, but is not the full picture. Going down a bit deeper (residual analysis), can give us more clarity on where we are the wrongest, and perhaps, a hint on how to be less wrong. Other metrics are available too to understand the quality of the fit. Plotting fits and data can be misleading, but more on that another time. See you next time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2295fd94a89" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The problem with referencing when you think you are copying]]></title>
            <link>https://medium.com/@AleAlejandro1/the-problem-with-referencing-when-you-think-you-are-copying-13f53ff9e555?source=rss-685474db29ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/13f53ff9e555</guid>
            <category><![CDATA[copy]]></category>
            <category><![CDATA[reference]]></category>
            <category><![CDATA[deep-copy]]></category>
            <category><![CDATA[standard-library]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[AleAlejandro1]]></dc:creator>
            <pubDate>Mon, 13 Sep 2021 14:03:27 GMT</pubDate>
            <atom:updated>2021-10-05T09:16:37.254Z</atom:updated>
            <content:encoded><![CDATA[<p>Here’s the deal, many times I need to create some sample data structures (e.g. lists) to see if my functions are doing what I want. Sometimes, I would want to check few different things on the same list and this is where I run into this issue the most. Take a look:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dl1%252520%25253D%252520%25255B1%25252C2%25252C3%25255D%25250Al2%252520%25253D%252520l1%25250Al1.append%25280%2529%25250Aprint%2528l2%2529%25250A%252523%252520%25255B1%25252C%2525202%25252C%2525203%25252C%2525200%25255D%25250A%252520%25250A%25250A&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dl1%25252520%2525253D%25252520%2525255B1%2525252C2%2525252C3%2525255D%2525250Al2%25252520%2525253D%25252520l1%2525250Al1.append%2525280%252529%2525250Aprint%252528l2%252529%2525250A%25252523%25252520%2525255B1%2525252C%252525202%2525252C%252525203%2525252C%252525200%2525255D%2525250A%25252520%2525250A%2525250A&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0debbe4d614089051fec4a655180eb8/href">https://medium.com/media/c0debbe4d614089051fec4a655180eb8/href</a></iframe><p>Ok so what just happened is that I incorrectly thought I was making a copy of l2. This would have allowed me to have 2 different lists that I can do things to independently. No, that’s not how it works. Here are the <a href="https://docs.python.org/3/library/copy.html">docs</a></p><p>First line creates a list object with some data inside and assigns it to “l1”. This means that there is now a reference created between the place in memory where the list object is stored and the variable “l1”. When I run the 2nd line, I am assigning “l2” to the same place in memory where the same list object is stored. This means, that effectively “l1” and “l2” are two names for the same thing. That’s why any change you make in one affects the other and vice-versa, because they are the same thing. You can check they are the same thing:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%25253E%25253E%25253E%252520id%2528l1%2529%25250A4468022592%25250A%25253E%25253E%25253E%252520id%2528l2%2529%25250A4468022592%25250A%25250A&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%2525253E%2525253E%2525253E%25252520id%252528l1%252529%2525250A4468022592%2525250A%2525253E%2525253E%2525253E%25252520id%252528l2%252529%2525250A4468022592%2525250A%2525250A&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/39fd753d5fcc6455c37461514c6579d7/href">https://medium.com/media/39fd753d5fcc6455c37461514c6579d7/href</a></iframe><p>The “id” command can be used to obtain the identity of an object. It will give you unique id of the element while it exists. If the item is removed from memory, something else might take its ID (like recycling cellphone numbers) but that’s not the main takeaway here. I want to be able to make copies, so what to do?</p><p>Enter “copy”. It has 2 flavours, <em>copy.copy()</em> and <em>copy.deepcopy()</em>. First one can be described as shallow copy and it will keep things different before you go into deeper levels. See below for shallow copy:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%25253E%25253E%25253Eimport%252520copy%25250A%25253E%25253E%25253E%252520L1%252520%25253D%252520%25255B%25255B1%25252C2%25255D%25252C%25255B3%25252C4%25255D%25255D%25250A%25253E%25253E%25253E%252520L2%252520%25253D%252520copy.copy%2528L1%2529%25250A%25250A%25253E%25253E%25253E%252520L1%25250A%25255B%25255B1%25252C%2525202%25255D%25252C%252520%25255B3%25252C%2525204%25255D%25255D%25250A%25253E%25253E%25253E%252520L2%25250A%25255B%25255B1%25252C%2525202%25255D%25252C%252520%25255B3%25252C%2525204%25255D%25255D%25250A%25250A%25253E%25253E%25253E%252520L1.append%2528%25255B5%25252C6%25255D%2529%25250A%25253E%25253E%25253E%252520L1%25250A%25255B%25255B1%25252C%2525202%25255D%25252C%252520%25255B3%25252C%2525204%25255D%25252C%252520%25255B5%25252C%2525206%25255D%25255D%25250A%25253E%25253E%25253E%252520L2%25250A%25255B%25255B1%25252C%2525202%25255D%25252C%252520%25255B3%25252C%2525204%25255D%25255D%25250A%25250A%25253E%25253E%25253E%252520L1%25255B0%25255D%25255B0%25255D%25253D99%25250A%25253E%25253E%25253E%252520L1%25250A%25255B%25255B99%25252C%2525202%25255D%25252C%252520%25255B3%25252C%2525204%25255D%25252C%252520%25255B5%25252C%2525206%25255D%25255D%25250A%25253E%25253E%25253E%252520L2%25250A%25255B%25255B99%25252C%2525202%25255D%25252C%252520%25255B3%25252C%2525204%25255D%25255D&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%2525253E%2525253E%2525253Eimport%25252520copy%2525250A%2525253E%2525253E%2525253E%25252520L1%25252520%2525253D%25252520%2525255B%2525255B1%2525252C2%2525255D%2525252C%2525255B3%2525252C4%2525255D%2525255D%2525250A%2525253E%2525253E%2525253E%25252520L2%25252520%2525253D%25252520copy.copy%252528L1%252529%2525250A%2525250A%2525253E%2525253E%2525253E%25252520L1%2525250A%2525255B%2525255B1%2525252C%252525202%2525255D%2525252C%25252520%2525255B3%2525252C%252525204%2525255D%2525255D%2525250A%2525253E%2525253E%2525253E%25252520L2%2525250A%2525255B%2525255B1%2525252C%252525202%2525255D%2525252C%25252520%2525255B3%2525252C%252525204%2525255D%2525255D%2525250A%2525250A%2525253E%2525253E%2525253E%25252520L1.append%252528%2525255B5%2525252C6%2525255D%252529%2525250A%2525253E%2525253E%2525253E%25252520L1%2525250A%2525255B%2525255B1%2525252C%252525202%2525255D%2525252C%25252520%2525255B3%2525252C%252525204%2525255D%2525252C%25252520%2525255B5%2525252C%252525206%2525255D%2525255D%2525250A%2525253E%2525253E%2525253E%25252520L2%2525250A%2525255B%2525255B1%2525252C%252525202%2525255D%2525252C%25252520%2525255B3%2525252C%252525204%2525255D%2525255D%2525250A%2525250A%2525253E%2525253E%2525253E%25252520L1%2525255B0%2525255D%2525255B0%2525255D%2525253D99%2525250A%2525253E%2525253E%2525253E%25252520L1%2525250A%2525255B%2525255B99%2525252C%252525202%2525255D%2525252C%25252520%2525255B3%2525252C%252525204%2525255D%2525252C%25252520%2525255B5%2525252C%252525206%2525255D%2525255D%2525250A%2525253E%2525253E%2525253E%25252520L2%2525250A%2525255B%2525255B99%2525252C%252525202%2525255D%2525252C%25252520%2525255B3%2525252C%252525204%2525255D%2525255D&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/86b8e327f20699d5d82933dc17518bac/href">https://medium.com/media/86b8e327f20699d5d82933dc17518bac/href</a></iframe><p>Which is not exactly giving me a ton of comfort. When I definitely want to make sure I am cloning and making 2 independent objects that are linked in no way, I use DEEP COPY:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%25253E%25253E%25253E%252520D1%252520%25253D%252520%25255B%252520%25255B%25255B%25255B%25255B0%25255D%25255D%25255D%25255D%25252C%2525201%25255D%25250A%25253E%25253E%25253E%252520D1%25250A%25255B%25255B%25255B%25255B%25255B0%25255D%25255D%25255D%25255D%25252C%2525201%25255D%25250A%25253E%25253E%25253E%252520D2%252520%25253D%252520copy.deepcopy%2528D1%2529%25250A%25253E%25253E%25253E%252520D1%25255B0%25255D%25255B0%25255D%25255B0%25255D%25255B0%25255D%25255B0%25255D%25250A0%25250A%25253E%25253E%25253E%252520D1%25255B0%25255D%25255B0%25255D%25255B0%25255D%25255B0%25255D%25255B0%25255D%252520%25253D%25252099%25250A%25253E%25253E%25253E%252520D1%25250A%25255B%25255B%25255B%25255B%25255B99%25255D%25255D%25255D%25255D%25252C%2525201%25255D%25250A%25253E%25253E%25253E%252520D2%25250A%25255B%25255B%25255B%25255B%25255B0%25255D%25255D%25255D%25255D%25252C%2525201%25255D&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%2525253E%2525253E%2525253E%25252520D1%25252520%2525253D%25252520%2525255B%25252520%2525255B%2525255B%2525255B%2525255B0%2525255D%2525255D%2525255D%2525255D%2525252C%252525201%2525255D%2525250A%2525253E%2525253E%2525253E%25252520D1%2525250A%2525255B%2525255B%2525255B%2525255B%2525255B0%2525255D%2525255D%2525255D%2525255D%2525252C%252525201%2525255D%2525250A%2525253E%2525253E%2525253E%25252520D2%25252520%2525253D%25252520copy.deepcopy%252528D1%252529%2525250A%2525253E%2525253E%2525253E%25252520D1%2525255B0%2525255D%2525255B0%2525255D%2525255B0%2525255D%2525255B0%2525255D%2525255B0%2525255D%2525250A0%2525250A%2525253E%2525253E%2525253E%25252520D1%2525255B0%2525255D%2525255B0%2525255D%2525255B0%2525255D%2525255B0%2525255D%2525255B0%2525255D%25252520%2525253D%2525252099%2525250A%2525253E%2525253E%2525253E%25252520D1%2525250A%2525255B%2525255B%2525255B%2525255B%2525255B99%2525255D%2525255D%2525255D%2525255D%2525252C%252525201%2525255D%2525250A%2525253E%2525253E%2525253E%25252520D2%2525250A%2525255B%2525255B%2525255B%2525255B%2525255B0%2525255D%2525255D%2525255D%2525255D%2525252C%252525201%2525255D&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b14d6b3a2daafd1f0b19e071598bfa97/href">https://medium.com/media/b14d6b3a2daafd1f0b19e071598bfa97/href</a></iframe><p>In this way, no matter how deep the child objects go, there will be no links between the lists. Ultimately, the actual core objects (e.g. the number “9”) will have a unique place in memory. But you won’t be changing that, so it’s fine.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%25253E%25253E%25253E%252520id%25289%2529%25250A4529638160%25250A%25253E%25253E%25253E%252520X%252520%25253D%2525209%25250A%25253E%25253E%25253E%252520id%2528X%2529%25250A4529638160%25250A%25253E%25253E%25253E%252520Z%25253D%25255B%25255B9%25255D%25255D%25250A%25253E%25253E%25253E%252520id%2528Z%25255B0%25255D%25255B0%25255D%2529%25250A4529638160&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%2525253E%2525253E%2525253E%25252520id%2525289%252529%2525250A4529638160%2525250A%2525253E%2525253E%2525253E%25252520X%25252520%2525253D%252525209%2525250A%2525253E%2525253E%2525253E%25252520id%252528X%252529%2525250A4529638160%2525250A%2525253E%2525253E%2525253E%25252520Z%2525253D%2525255B%2525255B9%2525255D%2525255D%2525250A%2525253E%2525253E%2525253E%25252520id%252528Z%2525255B0%2525255D%2525255B0%2525255D%252529%2525250A4529638160&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5c64e667c3743d22ec80cfb6fdcdb78/href">https://medium.com/media/a5c64e667c3743d22ec80cfb6fdcdb78/href</a></iframe><p>Finally, what is the “copy” method that is available in the standard library?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%25253E%25253E%25253E%252520A%252520%25253D%252520%25255B10%25252C10%25252C10%25255D%25250A%25253E%25253E%25253E%252520B%252520%25253D%252520A.copy%2528%2529%25250A%25253E%25253E%25253E%252520A%25250A%25255B10%25252C%25252010%25252C%25252010%25255D%25250A%25253E%25253E%25253E%252520B%25250A%25255B10%25252C%25252010%25252C%25252010%25255D&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%2525253E%2525253E%2525253E%25252520A%25252520%2525253D%25252520%2525255B10%2525252C10%2525252C10%2525255D%2525250A%2525253E%2525253E%2525253E%25252520B%25252520%2525253D%25252520A.copy%252528%252529%2525250A%2525253E%2525253E%2525253E%25252520A%2525250A%2525255B10%2525252C%2525252010%2525252C%2525252010%2525255D%2525250A%2525253E%2525253E%2525253E%25252520B%2525250A%2525255B10%2525252C%2525252010%2525252C%2525252010%2525255D&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/120efeb45b6ec6106ef3ad03ca40831e/href">https://medium.com/media/120efeb45b6ec6106ef3ad03ca40831e/href</a></iframe><p>Turns out that the “.copy()” method is available on Python 3 and it creates a shallow copy. There are other (some more non-sensical) ways of copying such as B = A[:] . You can check it out in this stack overflow post: <a href="https://stackoverflow.com/questions/2612802/list-changes-unexpectedly-after-assignment-why-is-this-and-how-can-i-prevent-it">LINK</a></p><p>Takeaway → “=” is not what you think it is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tnJOL3YmiIKyN_dts4B3tg.jpeg" /><figcaption>These are not the same object twice. They can be found in Kuala Lumpur.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13f53ff9e555" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API drama with book publishing]]></title>
            <link>https://medium.com/@AleAlejandro1/api-drama-with-book-publishing-adb992407747?source=rss-685474db29ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/adb992407747</guid>
            <category><![CDATA[beautifulsoup]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[open-library]]></category>
            <dc:creator><![CDATA[AleAlejandro1]]></dc:creator>
            <pubDate>Mon, 06 Sep 2021 07:53:30 GMT</pubDate>
            <atom:updated>2021-09-06T07:53:30.242Z</atom:updated>
            <content:encoded><![CDATA[<p>As I experiment with little bits of capability in Python for Data Science, I find little bits of ‘good to know’ stuff I want to share. In this case, some lessons learned first hand from scraping publish dates of books. A supposedly innocent task.</p><p><strong>Defining functions to talk to APIs:</strong></p><p>In Python, the <em>requests</em> package is your one-stop source of content from the outside world. For processing the html you retrieved, I am using <em>Beautiful Soup</em>.</p><p>As you can imagine, servers don’t like to be bothered (especially free and open ones) so if you spam a server with lots of requests you might get banned for a while.</p><blockquote>Takeaway : Structure your work with APIs so that you call the API once, then you do the experimenting offline with whatever was retrieved.</blockquote><p>The data is dirty. This is a healthy assumption, meaning that there will be missing values, there will be changes of pattern, etc. This means that you need to expect the unexpected. Testing your API with a few examples is not enough to be confident that you can run it 1000 times and always get the same types of results. See example below:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dimport%252520requests%25250Afrom%252520bs4%252520import%252520BeautifulSoup%25250Aimport%252520re%25250A%25250Adef%252520library_soup_isbn13%2528isbn13%2529%25253A%25250A%252520%252520%252520%252520%2527%2527%2527%25250A%252520%252520%252520%252520Function%252520to%252520query%252520for%252520a%252520isbn13%252520and%252520scrape%252520website%25252C%252520using%252520%25250A%252520%252520%252520%252520requests%252520and%252520beautiful%252520soup.%252520Returns%252520a%252520soup.%25250A%252520%252520%252520%252520%2527%2527%2527%25250A%252520%252520%252520%252520url%252520%25253D%252520f%2527https%25253A%25252F%25252Fopenlibrary.org%25252Fisbn%25252F%25257Bisbn13%25257D%2527%25250A%252520%252520%252520%252520response%252520%25253D%252520requests.get%2528url%2529%25250A%252520%252520%252520%252520soup%252520%25253D%252520BeautifulSoup%2528response.content%25252C%252520%252522html.parser%252522%2529%25250A%252520%252520%252520%252520return%252520soup%25250A%25250Adef%252520book_stats%2528isbn13%25252Csoup%2529%25253A%25250A%252520%252520%252520%252520%2527%2527%2527%25250A%252520%252520%252520%252520Function%252520that%252520takes%252520isbn13%252520and%252520soup%25252C%252520from%252520here%252520you%252520can%252520%25250A%252520%252520%252520%252520find%252520the%252520info%252520you%252520need%252520to%252520scrape%252520and%252520parse%252520it%252520into%252520a%252520dictionary.%25250A%252520%252520%252520%252520%2527%2527%2527%25250A%252520%252520%252520%252520publish_date%252520%25253D%252520soup.find_all%2528%252522div%252522%25252C%252520class_%25253D%252522edition-omniline%252522%2529%25255B0%25255D.find%2528%2527h4%2527%2529.find%2528%2527strong%2527%2529.string%25250A%252520%252520%252520%252520return%252520%25257B%2527isbn13%2527%25253Aisbn13%25252C%252520%2527publish_date%2527%25253Apublish_date%25257D%25250A%252520%252520%252520%252520%25250Aisbn13%25253D%25279780764585975%2527%25250Asoup%252520%25253D%252520library_soup_isbn%2528isbn13%2529%25250Atemp_stats%252520%25253D%252520book_stats%2528isbn13%25252Csoup%2529%25250Atemp_stats%252520%252523%252523%252520Returns%252520this%252520%25257B%2527isbn13%2527%25253A%252520%25279780764585975%2527%25252C%252520%2527publish_date%2527%25253A%2525202000%25257D%25250A&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dimport%25252520requests%2525250Afrom%25252520bs4%25252520import%25252520BeautifulSoup%2525250Aimport%25252520re%2525250A%2525250Adef%25252520library_soup_isbn13%252528isbn13%252529%2525253A%2525250A%25252520%25252520%25252520%25252520%252527%252527%252527%2525250A%25252520%25252520%25252520%25252520Function%25252520to%25252520query%25252520for%25252520a%25252520isbn13%25252520and%25252520scrape%25252520website%2525252C%25252520using%25252520%2525250A%25252520%25252520%25252520%25252520requests%25252520and%25252520beautiful%25252520soup.%25252520Returns%25252520a%25252520soup.%2525250A%25252520%25252520%25252520%25252520%252527%252527%252527%2525250A%25252520%25252520%25252520%25252520url%25252520%2525253D%25252520f%252527https%2525253A%2525252F%2525252Fopenlibrary.org%2525252Fisbn%2525252F%2525257Bisbn13%2525257D%252527%2525250A%25252520%25252520%25252520%25252520response%25252520%2525253D%25252520requests.get%252528url%252529%2525250A%25252520%25252520%25252520%25252520soup%25252520%2525253D%25252520BeautifulSoup%252528response.content%2525252C%25252520%25252522html.parser%25252522%252529%2525250A%25252520%25252520%25252520%25252520return%25252520soup%2525250A%2525250Adef%25252520book_stats%252528isbn13%2525252Csoup%252529%2525253A%2525250A%25252520%25252520%25252520%25252520%252527%252527%252527%2525250A%25252520%25252520%25252520%25252520Function%25252520that%25252520takes%25252520isbn13%25252520and%25252520soup%2525252C%25252520from%25252520here%25252520you%25252520can%25252520%2525250A%25252520%25252520%25252520%25252520find%25252520the%25252520info%25252520you%25252520need%25252520to%25252520scrape%25252520and%25252520parse%25252520it%25252520into%25252520a%25252520dictionary.%2525250A%25252520%25252520%25252520%25252520%252527%252527%252527%2525250A%25252520%25252520%25252520%25252520publish_date%25252520%2525253D%25252520soup.find_all%252528%25252522div%25252522%2525252C%25252520class_%2525253D%25252522edition-omniline%25252522%252529%2525255B0%2525255D.find%252528%252527h4%252527%252529.find%252528%252527strong%252527%252529.string%2525250A%25252520%25252520%25252520%25252520return%25252520%2525257B%252527isbn13%252527%2525253Aisbn13%2525252C%25252520%252527publish_date%252527%2525253Apublish_date%2525257D%2525250A%25252520%25252520%25252520%25252520%2525250Aisbn13%2525253D%2525279780764585975%252527%2525250Asoup%25252520%2525253D%25252520library_soup_isbn%252528isbn13%252529%2525250Atemp_stats%25252520%2525253D%25252520book_stats%252528isbn13%2525252Csoup%252529%2525250Atemp_stats%25252520%25252523%25252523%25252520Returns%25252520this%25252520%2525257B%252527isbn13%252527%2525253A%25252520%2525279780764585975%252527%2525252C%25252520%252527publish_date%252527%2525253A%252525202000%2525257D%2525250A&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f69837a26809997eebfd698a43e9ba9c/href">https://medium.com/media/f69837a26809997eebfd698a43e9ba9c/href</a></iframe><p>If you take a look into the book_stats function, you’ll notice that I have identified under which class/h4 section in the html the date of publishing is found. Job done? NO.</p><p>If you query few ISBN13 (that is, few different books) you’ll get a range of answers for date of publishing:</p><pre>9780743201117 - &#39;October 31, 2000&#39;<br>9780312863555 - &#39;1997&#39;<br>9780439785969 - &#39;2006-09&#39;<br>9780439554893 - &#39;Nov 01, 2003&#39;</pre><p>This is straight-up evil, but you need to be expecting this type of behaviour. This will be especially painful if your first 5 attempts are all following the same structure and they change around iteration 112/1000. You are probably very far away from the computer at this point, which will make the pain much greater when you come and check your scraping.</p><p>Consider using <em>strip</em>, <em>split</em> and especially <em>re</em> to isolate the data you want based on the possible known patterns. If something unexpected happens, try passing a default value so the scraping can continue and you can later investigate the odd-ones.</p><blockquote>Takeaway: Address patterns that you know. Handle the ones you don’t.</blockquote><p>Finally, some APIs might allow you to send multiple queries at once. Since the API calls is likely the biggest time consumer of the scraping application, being able to carry out the requests faster is a sure way to speed up your function execution. As always, remember to <a href="https://medium.com/@AleAlejandro1/apis-the-superpower-you-didnt-know-you-had-a8972ed3b1ad">read the docs</a>, as much of the things you need to know from an API are to be found there. Some things, might not. That leads you to trial-and-error (e.g. how many queries at once you can send in a single call) to discover.</p><p>Stay safe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rKixuH3qfhvDaI7JBQAyRA.jpeg" /><figcaption>Lots of books waiting to be scraped.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adb992407747" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[APIs : the superpower you didn’t know you had]]></title>
            <link>https://medium.com/@AleAlejandro1/apis-the-superpower-you-didnt-know-you-had-a8972ed3b1ad?source=rss-685474db29ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8972ed3b1ad</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[requests-library]]></category>
            <dc:creator><![CDATA[AleAlejandro1]]></dc:creator>
            <pubDate>Wed, 25 Aug 2021 15:24:07 GMT</pubDate>
            <atom:updated>2021-08-25T15:24:07.920Z</atom:updated>
            <content:encoded><![CDATA[<h3>APIs : the superpower you didn’t know you had</h3><p>I would have to say that my favorite part of using an API is just having to write a couple lines and leverage on the large amounts of code, compute and someone else’s resources (money, time, etc.) so I can feel like a total badass with minimum effort.</p><p>You should try it. Here:</p><p>Let’s get the latitude and longitude of some location. You could use google maps for that, but we can rely on <a href="https://nominatim.openstreetmap.org/ui/search.html">Nominatim</a> (which is “the debugging interface for the search engine used on the OpenStreetMap website”). To interact with servers like this in Python, we are going to use the requests library, understand the syntax for our query and if the API is free to use, that’s about it.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Durl%252520%25253D%252520%2527https%25253A%25252F%25252Fnominatim.openstreetmap.org%25252Fsearch%25253F%2527%25250Aquery%252520%25253D%252520%2527q%25253DEiffel%25252BTower%2527%25250Aparams%25253D%252522format%25253Djson%252526addressdetails%25253D1%252522%25250Aresponse%252520%25253D%252520requests.get%2528url%25252Bquery%25252B%2527%252526%2527%25252Bparams%2529.json%2528%2529%25250Aprint%2528f%2527Latitude%252520is%25253A%252520%25257Bresponse%25255B0%25255D%25255B%252522lat%252522%25255D%25257D%252520and%252520Longitude%252520is%252520%25257Bresponse%25255B0%25255D%25255B%252522lon%252522%25255D%25257D%2527%2529%25250A%252523Gives%252520you%252520--%25253E%252520Latitude%252520is%25253A%25252048.858260200000004%252520and%252520Longitude%252520is%2525202.2944990543196795&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Durl%25252520%2525253D%25252520%252527https%2525253A%2525252F%2525252Fnominatim.openstreetmap.org%2525252Fsearch%2525253F%252527%2525250Aquery%25252520%2525253D%25252520%252527q%2525253DEiffel%2525252BTower%252527%2525250Aparams%2525253D%25252522format%2525253Djson%25252526addressdetails%2525253D1%25252522%2525250Aresponse%25252520%2525253D%25252520requests.get%252528url%2525252Bquery%2525252B%252527%25252526%252527%2525252Bparams%252529.json%252528%252529%2525250Aprint%252528f%252527Latitude%25252520is%2525253A%25252520%2525257Bresponse%2525255B0%2525255D%2525255B%25252522lat%25252522%2525255D%2525257D%25252520and%25252520Longitude%25252520is%25252520%2525257Bresponse%2525255B0%2525255D%2525255B%25252522lon%25252522%2525255D%2525257D%252527%252529%2525250A%25252523Gives%25252520you%25252520--%2525253E%25252520Latitude%25252520is%2525253A%2525252048.858260200000004%25252520and%25252520Longitude%25252520is%252525202.2944990543196795&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/cebf864fde36b4849e195078f4e1f163/href">https://medium.com/media/cebf864fde36b4849e195078f4e1f163/href</a></iframe><p>How easy was that?</p><p>So let’s analyse what just happened.</p><p>A) An API (made by smart people) was identified, the <a href="https://nominatim.org/release-docs/latest/api/Search/">docs</a> were ‘scanned’ for syntax and examples.</p><p>B) Structure a query so that is possible to programatically concatenate everything. Probably you want to define a function that will take the search query and wrap it with the right syntax. I didn’t do this here because I was lazy.</p><p>C) Use the requests library to perform a GET request and process it as a JSON we can consume in python as a dictionary.</p><p>D) Find the info you want in the dictionary and do stuff with it. Good old coding!.</p><p>E) Experience the slightest rush of megalomania by realising how much more you can do if you simply find the right APIs.</p><p>How will you use this power?</p><p>Have a nice day</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PhhXUJnte_9sw79VORJn0Q.jpeg" /><figcaption>Latitude is: 48.858260200000004 and Longitude is 2.2944990543196795</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8972ed3b1ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Read the docs: Python string methods]]></title>
            <link>https://medium.com/@AleAlejandro1/read-the-docs-python-string-methods-b718834c21fd?source=rss-685474db29ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/b718834c21fd</guid>
            <category><![CDATA[string-methods]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[AleAlejandro1]]></dc:creator>
            <pubDate>Thu, 19 Aug 2021 10:56:48 GMT</pubDate>
            <atom:updated>2021-08-20T01:47:17.223Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello, 1st post here in medium, great idea. Allow me to cut to the chase.</p><p>I’m writing here to capture some realisations I’m getting as I move inwards into hands-on data wrangling. I will rely on Python as programming language. I’ll be needing a way to represent code nicely, so that it can be copy-pasted effortlessly, so I’ll be doing this:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dnumber%252520%25253D%252520123%25250Aprint%2528f%2527Hello%252520this%252520is%252520an%252520example%252520of%252520python%252520code.%252520Number%252520is%252520%25257Bnumber%25257D%2527%2529&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dnumber%25252520%2525253D%25252520123%2525250Aprint%252528f%252527Hello%25252520this%25252520is%25252520an%25252520example%25252520of%25252520python%25252520code.%25252520Number%25252520is%25252520%2525257Bnumber%2525257D%252527%252529&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd95d70f4473d6026927cf1a52221be9/href">https://medium.com/media/fd95d70f4473d6026927cf1a52221be9/href</a></iframe><p>The topic of this post is on ‘<em>why a reluctance to use standard libraries holds you back</em>’. If you are used to hack your way around to get tailored solutions, you will quickly realise that this behaviour doesn’t scale. An example of this is taking a string that contains a sentence and make a list of words out of it. To achieve this, you could just use the <strong>split</strong> string method using “ “ as the separator and keep the list you get in return.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dsentence%252520%25253D%252520%2527This%252520is%252520an%252520example.%2527%25250Awords%252520%25253D%252520sentence.split%2528%2529%25250Aprint%2528words%2529%25250A%252523%252520gets%252520you%252520--%25253E%252520%25255B%2527This%2527%25252C%252520%2527is%2527%25252C%252520%2527an%2527%25252C%252520%2527example.%2527%25255D&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dsentence%25252520%2525253D%25252520%252527This%25252520is%25252520an%25252520example.%252527%2525250Awords%25252520%2525253D%25252520sentence.split%252528%252529%2525250Aprint%252528words%252529%2525250A%25252523%25252520gets%25252520you%25252520--%2525253E%25252520%2525255B%252527This%252527%2525252C%25252520%252527is%252527%2525252C%25252520%252527an%252527%2525252C%25252520%252527example.%252527%2525255D&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cb43056e5c0770a84c336c0dd7621ff/href">https://medium.com/media/3cb43056e5c0770a84c336c0dd7621ff/href</a></iframe><p>Pretty good. Just make all lower case, remove the ‘.’ in the last element of the list and you are done. We can <em>confidently</em> define a function to automate this and call it a day:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Ddef%252520give_me_words%2528sentence%2529%25253A%25250A%252520%252520%252520%252520words%25253Dsentence.split%2528%2527%252520%2527%2529%252520%252523%252520split%252520in%252520elements%252520on%252520a%252520list%25250A%252520%252520%252520%252520%25250A%252520%252520%252520%252520for%252520i%25252Cword%252520in%252520enumerate%2528words%2529%25253A%25250A%252520%252520%252520%252520%252520%252520%252520%252520words%25255Bi%25255D%252520%25253D%252520word.lower%2528%2529%252520%252523%252520make%252520every%252520word%252520lower%252520case%25250A%252520%252520%252520%252520words%25255B-1%25255D%25253Dwords%25255B-1%25255D%25255B%25253A-1%25255D%252520%252523%252520take%252520the%252520last%252520word%252520and%252520remove%252520the%252520last%252520char%252520on%252520it%25250A%252520%252520%252520%252520return%252520words%252520%252523%252520profit%25250A%252520%252520%252520%252520%25250Amy_sentence%252520%25253D%252520%2527This%252520is%252520an%252520example.%2527%25250Agive_me_words%2528my_sentence%2529%25250A%252523%252520gets%252520you%252520--%25253E%252520%25255B%2527this%2527%25252C%252520%2527is%2527%25252C%252520%2527an%2527%25252C%252520%2527example%2527%25255D&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Ddef%25252520give_me_words%252528sentence%252529%2525253A%2525250A%25252520%25252520%25252520%25252520words%2525253Dsentence.split%252528%252527%25252520%252527%252529%25252520%25252523%25252520split%25252520in%25252520elements%25252520on%25252520a%25252520list%2525250A%25252520%25252520%25252520%25252520%2525250A%25252520%25252520%25252520%25252520for%25252520i%2525252Cword%25252520in%25252520enumerate%252528words%252529%2525253A%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520words%2525255Bi%2525255D%25252520%2525253D%25252520word.lower%252528%252529%25252520%25252523%25252520make%25252520every%25252520word%25252520lower%25252520case%2525250A%25252520%25252520%25252520%25252520words%2525255B-1%2525255D%2525253Dwords%2525255B-1%2525255D%2525255B%2525253A-1%2525255D%25252520%25252523%25252520take%25252520the%25252520last%25252520word%25252520and%25252520remove%25252520the%25252520last%25252520char%25252520on%25252520it%2525250A%25252520%25252520%25252520%25252520return%25252520words%25252520%25252523%25252520profit%2525250A%25252520%25252520%25252520%25252520%2525250Amy_sentence%25252520%2525253D%25252520%252527This%25252520is%25252520an%25252520example.%252527%2525250Agive_me_words%252528my_sentence%252529%2525250A%25252523%25252520gets%25252520you%25252520--%2525253E%25252520%2525255B%252527this%252527%2525252C%25252520%252527is%252527%2525252C%25252520%252527an%252527%2525252C%25252520%252527example%252527%2525255D&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe6f628f380f48ef16bc72481d38f780/href">https://medium.com/media/fe6f628f380f48ef16bc72481d38f780/href</a></iframe><p>It worked! the thing is, if you test this function (always test), you need to imagine that whoever is providing the input sentence is your enemy. So let’s see what the enemy can do:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Ds1%252520%25253D%252520%2527%252520Hello%252520%252520%252520%252520I%252520am%252520a.%252520Sentence%252520.%252520%2527%25250As2%252520%25253D%252520%2527lol%2527%25250As3%252520%25253D%252520%2527%252520%2527%25250A%25250Aprint%2528give_me_words%2528s1%2529%2529%252520%252523%252520you%252520get%252520--%25253E%252520%25255B%2527%2527%25252C%252520%2527hello%2527%25252C%252520%2527%2527%25252C%252520%2527%2527%25252C%252520%2527%2527%25252C%252520%2527i%2527%25252C%252520%2527am%2527%25252C%252520%2527a.%2527%25252C%252520%2527sentence%2527%25252C%252520%2527.%2527%25252C%252520%2527%2527%25255D%25250Aprint%2528give_me_words%2528s2%2529%2529%252520%252523%252520you%252520get%252520--%25253E%252520%25255B%2527lo%2527%25255D%25250Aprint%2528give_me_words%2528s3%2529%2529%252520%252523%252520you%252520get%252520--%25253E%252520%25255B%2527%2527%25252C%252520%2527%2527%25255D&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Ds1%25252520%2525253D%25252520%252527%25252520Hello%25252520%25252520%25252520%25252520I%25252520am%25252520a.%25252520Sentence%25252520.%25252520%252527%2525250As2%25252520%2525253D%25252520%252527lol%252527%2525250As3%25252520%2525253D%25252520%252527%25252520%252527%2525250A%2525250Aprint%252528give_me_words%252528s1%252529%252529%25252520%25252523%25252520you%25252520get%25252520--%2525253E%25252520%2525255B%252527%252527%2525252C%25252520%252527hello%252527%2525252C%25252520%252527%252527%2525252C%25252520%252527%252527%2525252C%25252520%252527%252527%2525252C%25252520%252527i%252527%2525252C%25252520%252527am%252527%2525252C%25252520%252527a.%252527%2525252C%25252520%252527sentence%252527%2525252C%25252520%252527.%252527%2525252C%25252520%252527%252527%2525255D%2525250Aprint%252528give_me_words%252528s2%252529%252529%25252520%25252523%25252520you%25252520get%25252520--%2525253E%25252520%2525255B%252527lo%252527%2525255D%2525250Aprint%252528give_me_words%252528s3%252529%252529%25252520%25252523%25252520you%25252520get%25252520--%2525253E%25252520%2525255B%252527%252527%2525252C%25252520%252527%252527%2525255D&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a42625d66fadbf45a9869c898fd8d7e7/href">https://medium.com/media/a42625d66fadbf45a9869c898fd8d7e7/href</a></iframe><p>Wow, pretty bad. And no errors are returned.. so you wouldn’t know something is wrong unless you checked. The enemy was able to defeat us very easily. So, now we know we need to come up with a more general solution. You could be inclined to roll up your sleeves and start coming up with tons of IF conditions to watch out for double spaces, or for punctuation in strange places.. but that’s a path that may lead to making a bad &amp; complicated function for something that smarter people have already made for you. It’s called the standard library for Python. Here! friend, use this <a href="https://docs.python.org/3/library/stdtypes.html#string-methods">link</a>.</p><p>Using string methods like <strong>split, lower </strong>and <strong>replace </strong>as well as list methods like<strong> remove </strong>we are able to defeat our enemy’s last attack (pass tests) by doing:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Ddef%252520give_me_words_please%2528sentence%2529%25253A%25250A%252520%252520%252520%252520new_sentence%252520%25253D%252520sentence.replace%2528%2527.%2527%25252C%2527%2527%2529%252520%252523%252520replace%252520all%252520%2527.%2527%252520with%252520%2527%2527%25250A%252520%252520%252520%252520words%25253Dnew_sentence.split%2528%2527%252520%2527%2529%252520%252523%252520split%252520by%252520spaces%25250A%252520%252520%252520%252520while%252520%2527%2527%252520in%252520words%25253A%252520%252523%252520remove%252520all%252520empty%252520strings%252520%25250A%252520%252520%252520%252520%252520%252520%252520%252520words.remove%2528%2527%2527%2529%25250A%252520%252520%252520%252520words%252520%25253D%252520%25255Bword.lower%2528%2529%252520for%252520word%252520in%252520words%25255D%252520%252523%252520list%252520comprehension%252520to%252520make%252520all%252520words%252520lowercase%252520in%252520one%252520line%25250A%252520%252520%252520%252520return%252520words%252520%252523%252520profit%25250A%25250Aprint%2528give_me_words_please%2528s1%2529%2529%252520%252523%252520you%252520get%252520--%25253E%252520%25255B%2527hello%2527%25252C%252520%2527i%2527%25252C%252520%2527am%2527%25252C%252520%2527a%2527%25252C%252520%2527sentence%2527%25255D%25250Aprint%2528give_me_words_please%2528s2%2529%2529%252520%252523%252520you%252520get%252520--%25253E%252520%25255B%2527lol%2527%25255D%25250Aprint%2528give_me_words_please%2528s3%2529%2529%252520%252523%252520you%252520get%252520--%25253E%252520%25255B%25255D&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Ddef%25252520give_me_words_please%252528sentence%252529%2525253A%2525250A%25252520%25252520%25252520%25252520new_sentence%25252520%2525253D%25252520sentence.replace%252528%252527.%252527%2525252C%252527%252527%252529%25252520%25252523%25252520replace%25252520all%25252520%252527.%252527%25252520with%25252520%252527%252527%2525250A%25252520%25252520%25252520%25252520words%2525253Dnew_sentence.split%252528%252527%25252520%252527%252529%25252520%25252523%25252520split%25252520by%25252520spaces%2525250A%25252520%25252520%25252520%25252520while%25252520%252527%252527%25252520in%25252520words%2525253A%25252520%25252523%25252520remove%25252520all%25252520empty%25252520strings%25252520%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520words.remove%252528%252527%252527%252529%2525250A%25252520%25252520%25252520%25252520words%25252520%2525253D%25252520%2525255Bword.lower%252528%252529%25252520for%25252520word%25252520in%25252520words%2525255D%25252520%25252523%25252520list%25252520comprehension%25252520to%25252520make%25252520all%25252520words%25252520lowercase%25252520in%25252520one%25252520line%2525250A%25252520%25252520%25252520%25252520return%25252520words%25252520%25252523%25252520profit%2525250A%2525250Aprint%252528give_me_words_please%252528s1%252529%252529%25252520%25252523%25252520you%25252520get%25252520--%2525253E%25252520%2525255B%252527hello%252527%2525252C%25252520%252527i%252527%2525252C%25252520%252527am%252527%2525252C%25252520%252527a%252527%2525252C%25252520%252527sentence%252527%2525255D%2525250Aprint%252528give_me_words_please%252528s2%252529%252529%25252520%25252523%25252520you%25252520get%25252520--%2525253E%25252520%2525255B%252527lol%252527%2525255D%2525250Aprint%252528give_me_words_please%252528s3%252529%252529%25252520%25252523%25252520you%25252520get%25252520--%2525253E%25252520%2525255B%2525255D&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/72dbbd1f2c679e280856dc9ec0142858/href">https://medium.com/media/72dbbd1f2c679e280856dc9ec0142858/href</a></iframe><p>Is this it? Is this the ultimate function to extract words from a sentence?. Definitely not. However, I’ve noticed two things I want to share:</p><p>a) Relying on methods makes the code neat and simple. No bells and whistles required. Trust that the smart people that invented <strong>split</strong> know what they are doing. Their code has been thoroughly tested.</p><p>b) A success factor for code is passing tests. It will allow you to make sure the code does what you want it to do. The less new lines you type the better, since every line is an opportunity to insert a weakness that your enemies can exploit. With this idea of building on top of good work from others, it feels like a good time to quote Newton:</p><blockquote>“If I have been able to see further, it was only because I stood on the shoulders of giants.” -Isaac Newton</blockquote><p>TL;DR :</p><blockquote>1- Look for standard methods and functions before you write your own.</blockquote><blockquote>2- Test every function you define before you plug it into something else.</blockquote><p>Bye for now</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*3U55OhrKsKyC-FPWggpYEA@2x.jpeg" /><figcaption>Don’t build your tools if you can avoid it. Build with tools.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b718834c21fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>