<?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 Emily Strong on Medium]]></title>
        <description><![CDATA[Stories by Emily Strong on Medium]]></description>
        <link>https://medium.com/@thedatanerd?source=rss-8ce2e316e1b2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*59CHn0eypDxQw4qwTLXlsQ.png</url>
            <title>Stories by Emily Strong on Medium</title>
            <link>https://medium.com/@thedatanerd?source=rss-8ce2e316e1b2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 07:54:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thedatanerd/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[What is a support vector?]]></title>
            <link>https://medium.com/the-data-nerd/what-is-a-support-vector-efe350a796c8?source=rss-8ce2e316e1b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/efe350a796c8</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Emily Strong]]></dc:creator>
            <pubDate>Wed, 20 Jul 2022 16:42:22 GMT</pubDate>
            <atom:updated>2022-07-20T16:42:22.861Z</atom:updated>
            <content:encoded><![CDATA[<p>Support vector machines are supervised machine learning models that are well-suited for high-dimensional data and still perform well when there are more dimensions than training data. (You do still need to be careful in choosing kernel functions and regularization for those situations, of course.)</p><p>So what is a support vector?</p><p>Let’s start with the concept of <strong>support</strong>. In mathematics, the support of a function is the set of elements that don’t map to zero when the function is applied. You may have encountered this before in classification metrics as the number of elements in the data used to calculate the metric that belong to each class — they are the support set for that class.</p><p>In SVM, we find the hyperplane that gives a <strong>maximal margin</strong> between the points of different classes that are closest together. Their proximity to the decision boundary makes them more difficult to classify, and so the hyperplane is defined by these points. This set of points are known as the <strong>support vectors</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P3PhcmmXC08OeBITPXi_ng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XoIL8igEcpWerzQBZodhow.png" /><figcaption><strong>Left image: </strong>the optimal hyperplane gives the maximum margin between the classes. <strong>Right image:</strong> the support vectors are the data points on the margin.</figcaption></figure><p>A key attribute of the hyperplane is its <strong>normal vector</strong>. This is used at inference to project new data points to determine where they fall relative to the hyperplane. If the dot product of the normal vector and the data point is greater than a constant (the bias of the model), then the data point is assigned the positive class for the hyperplane.</p><p>The normal vector of the maximal margin hyperplane is the sum of the support vectors. Thus, if one of the support vectors changes or is removed, the hyperplane and normal vector will change.</p><p>Support vectors and other key concepts for linear models in real-world settings are covered in my Machine Learning Flashcards: Linear Models deck. <a href="https://www.etsy.com/listing/1270922607/machine-learning-flashcards-linear">Check it out on Etsy</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efe350a796c8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-data-nerd/what-is-a-support-vector-efe350a796c8">What is a support vector?</a> was originally published in <a href="https://medium.com/the-data-nerd">The Data Nerd</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Better Python Programming for Data Scientists, Part 4: Introduction to Object-Oriented Programming]]></title>
            <link>https://medium.com/the-data-nerd/better-python-programming-for-data-scientists-part-4-introduction-to-object-oriented-programming-355f4287f103?source=rss-8ce2e316e1b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/355f4287f103</guid>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Emily Strong]]></dc:creator>
            <pubDate>Sat, 16 Jul 2022 03:23:54 GMT</pubDate>
            <atom:updated>2022-07-16T03:23:54.259Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JwRvKrLh8nwpeii7lDC7ng.png" /><figcaption>The 4 pillars of object-oriented programming</figcaption></figure><p>I will never forget the day in grad school when a friend admitted she was completely stuck on a homework assignment for our intermediate data science course. She had been at the top of the class in the introductory class, so this came as a surprise to me. The assignment involved working with a starter notebook that included a custom class, and my friend had never seen that style of programming before and had no idea how to use the code.</p><p>With the beginner-friendly documentation for libraries like scikit-learn and the wealth of tutorials available, it is very easy to successfully navigate working on data science projects for a long time without every learning object-oriented programming. But eventually the day comes when you can’t avoid it any longer, and if you have been treating these library APIs as something akin to magic, it can be deeply confusing.</p><p>In this series we’ve looked at Python fundamentals (parts <a href="https://medium.com/the-data-nerd/better-python-programming-for-data-scientists-part-1-python-fundamentals-5b76bc7d9000">1</a> and <a href="https://medium.com/the-data-nerd/better-python-programming-for-data-scientists-part-2-more-python-fundamentals-6ba076b65c0e">2</a>) and <a href="https://medium.com/the-data-nerd/better-python-programming-for-data-scientists-part-3-data-structures-eaee8c033c1c">data structures</a>. Now it’s time to leap in the world of object-oriented programming (or OOP).</p><h3>Classes and Objects</h3><p>Object-oriented programming is a paradigm that centers data rather than functions in its structure. What does that mean?</p><p>It means that if you want to, for example, create an address book app, your code is centered around containers for the necessary data, which in this case would be people, businesses, and other entities you might want to include in your address book.</p><p>This design involves two core components:</p><ul><li><strong>Classes</strong>: the abstract entity that will own data, have common attributes, and perform functions. In our example, people and businesses would be classes. They have names, addresses, phone numbers, and functionality might include retrieving (“getting”) or updating (“setting”) a phone number.</li><li><strong>Objects</strong>: the specific <strong>instances</strong> of classes (when you initialize a variable as an object, this is known as instantiation), that have data values associated with them. In our example, each individual person or business record is an object. You can get or set the name, phone number and address of each individual.</li></ul><p>If we look at a Python library like scikit-learn, each algorithm is a class. When you instantiate a model, you are creating an object of that class. If we wanted to create our own class, it would look something like the below code. In this example, we can create a classifier that assigns classes at random.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/738d77ac00063e5ad83bb49bf42eae33/href">https://medium.com/media/738d77ac00063e5ad83bb49bf42eae33/href</a></iframe><p>When working with object-oriented programming, you will often see property and attribute used interchangeably. They do have different meanings in Python though. An attribute is any variable that belongs to the class or object. A property is a special type of attribute that has __get__, __set__ and __delete__ methods and is created with the @property decorator as a function. Although they have functions, they are accessed in the same was as attributes (that is as object.property). This enables the property to not need to be declared and an initial value stored in the constructor. It is uncommon to need to create properties.</p><p>In my own work, I have had to use properties in the MABWiser library when I encountered a problem where our use of nested named tuples for two of our attributes was preventing us from being able to pickle our models because the pickle protocol doesn’t support nested classes. I changed the two attributes to be properties and in the property functions wrote logic to recreate the named tuples when accessed. This meant the named tuples were no longer stored, and we could safely pickle our models without losing functionality. You can see how this was implemented in the <a href="https://github.com/fidelity/mabwiser/blob/master/mabwiser/mab.py#L903">Github repository</a>.</p><h3>Data Abstraction and Inheritance</h3><p>Data abstraction comes from the idea that there is some functionality that an individual class shouldn’t need to deal with. This can be functionality that is common to multiple classes, or it might be the case that there are two or more separate entities that comprise the larger whole which has its own emergent functionality. Examples of this are the wheels, doors, and engine that come together as parts of a car, generic functionality that a classifier needs to have regardless of specific algorithm, or the individual decision trees that are components of a random forest.</p><p>Sometimes you’ll see this phrased as there being irrelevant or unimportant things the user doesn’t need to know or care about. In this case, “user” means the person writing a class and using other classes in the process, not an end-user of the library or API. The person writing our hypothetical car class cares that the wheel class has turn and roll functions but doesn’t care how they are implemented.</p><p>Data abstraction is the separation of functionality into other classes, “abstracting away” the details you don’t need to worry about in order to keep your implementation simple and efficient.</p><p>Often the details that can be abstracted away are things that are common to multiple classes. In our address book app example, we might have an abstraction of Entry that has properties such as name, address, and phone number, while a Business has hours and a contact person, and a Person has a birth date. If we think of our RandomClassifier, if we want to add parallelization to it, that is probably something we will want to add to other classifiers through a generic Classifier class.</p><p>This leads us to the idea of inheritance, the arrangement of a hierarchy in which <strong>child</strong> classes or <strong>subclasses</strong> inherit behavior and properties from <strong>parent </strong>or <strong>base</strong> classes. Inheritance only goes in one direction, so anything defined in the child class is not available in the parent class. They also can <strong>override </strong>the values and functions implemented in the parent class without impacting the parent or other child classes. If a function is implemented in the parent class, that parent functionality can still be accessed internally by calling super().function() within the overriding function of the child class.</p><p>In addition to implemented behavior and properties, API definitions can be inherited as <strong>abstract methods</strong>. That is, all child classes must implement a function with a predefined function signature. This ensures for example that all of your classifiers have fit and predict functions that take the same arguments. We can see an example of this below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2f821a97a4cd4238a1cadb4a9e0f5b1/href">https://medium.com/media/f2f821a97a4cd4238a1cadb4a9e0f5b1/href</a></iframe><p>Our example of RandomClassifier highlights a common challenge in inheritance — sometimes there are arguments required for certain child classes but not others. This is especially true for data science libraries where we want to have standardized APIs where algorithms can be used interchangeably in code without requiring updating your calls to fit and predict. Accepting the arguments and not using them is a simple solution that keeps the API consistent.</p><p>Another potential solution to this is known as <strong>overloading</strong>. Overloading specifically refers to having two or more functions with the same name but different function signatures. Python handles overloading by only using the last implementation of the function. If we implement the abstract methods of the parent class but omit the unneeded arguments, the new function signature will be used rather than the abstract one. As with overriding, the parent function can be accessed internally to the child class function by calling super().function(). If two versions of the same function are implemented within a single class, only the last one will be used.</p><p>For a real-world example of abstraction and inheritance in action, check out scikit-learn’s <a href="https://github.com/scikit-learn/scikit-learn/blob/main/sklearn/tree/_classes.py">source code for decision trees</a>. There is a BaseDecisionTree class that DecisionTreeClassifier and DecisionTreeRegressor inherit from. The generic decision tree functionality resides in the parent class, while the child classes deal with the functionality unique to each of them.</p><h3>Encapsulation</h3><p>Encapsulation actually means two closely related things in object-oriented programming:</p><ol><li>The grouping of data with the methods that operate on that data; and</li><li>The restriction of direct access to some components of the data and methods.</li></ol><p>If we think of a decision tree, the class for that will contain the tree data structure, all of the attributes of the tree such as the maximum depth and the number of leaves, and the hyperparameters that were provided, and it has the methods to compute these things and retrieve additional information such as feature importance. Everything we could possibly want to know about or do with a decision tree is encapsulated in this class.</p><p>There are some things, however, that the decision tree algorithm needs to know or needs to be able to do that the end user does not.</p><p>Every class, method and variable in Python is <strong>public</strong>. If you import *, every element in a class or module is imported and available for use (which is why importing * generally isn’t a good idea — you may not know all of the things you are importing and can have naming conflicts among other issues).</p><p>You may have seen methods and variables that have an underscore prefix. The single underscore (_name) means that it is <strong>protected</strong>. Protected attributes and methods are available for use in the class to which they belong and its child classes. As stated previously, everything in Python is public so it doesn’t stop you from using them external to the class, but it’s a way of signaling that you probably shouldn’t be using it.</p><p>There is also the double underscore (__name) which is used to <strong>mangle</strong> the name. When a mangled method or attribute is accessed outside the class including in a child class, the name is prefixed with _class to become _class__name. For example:</p><pre>class TestClass:<br>  def __test_func():<br>    print(&#39;test&#39;)</pre><pre>test_object = TestClass()</pre><pre># The function cannot be accessed externally under the original name<br>test_object.__test_func()<br>&gt;&gt; AttributeError: &#39;TestClass&#39; object has no attribute &#39;__test_func&#39;</pre><pre># The function can be accessed externally under the mangled name<br>test_object._TestClass__test_func()<br>&gt;&gt; &#39;test&#39;</pre><p>The idea behind mangling is to avoid name collisions in inheritance so that parent and child can each have their own implementations or values. This goes back to the idea of overriding. Mangling makes the parent class’s functionality externally available while allowing the child class to use the same name internally for a different method or value. The child class would thus have in its externally available attributes or methods _ChildClass__name and _ParentClass__name.</p><p>Some people use mangling for <strong>private</strong> attributes and methods, those only accessible within a single class. As with protected ones, Python doesn’t stop you from using these externally, but it can be a way of flagging them and the user does need to know to prefix the attribute or method with _class.</p><p>You can see all of the attributes and methods of an object, both public, protected, and mangled by calling dir(object).</p><h3>Polymorphism</h3><p>Our last topic in this introduction to object-oriented programming is one that has already been mentioned a few times and doesn’t require further in-depth exploration, but we haven’t put a name to it yet: <strong>polymorphism</strong> is using a single <strong>interface</strong> for multiple classes.</p><p>Data science libraries that have a standardized API for diverse algorithm classes to allow them to be used interchangeably are leveraging polymorphism. Abstract classes can be specifically defined as interfaces with no implemented methods for this purpose. Polymorphism can also include child classes that don’t implement an abstract class but do override the functionality of the parent class. The key idea is multiple classes all having the same API but their own implementations under the hood.</p><h3>Conclusion</h3><p>Given that object-oriented programming is an entire programming paradigm, it is a big topic and we have just scratched the surface. We’ve covered the four pillars of OOP: abstraction, encapsulation, inheritance,and polymorphism. Next time we will build on these foundational ideas and take a look at some object-oriented design patterns that you may find useful.</p><p>Stay tuned for the rest of the Better Python Programming for Data Scientists series!</p><p><a href="https://medium.com/the-data-nerd/better-python-programming-for-data-scientists-part-1-python-fundamentals-5b76bc7d9000">Python Fundamentals</a> | <a href="https://medium.com/the-data-nerd/better-python-programming-for-data-scientists-part-2-more-python-fundamentals-6ba076b65c0e">More Python Fundamentals</a> | <a href="https://medium.com/the-data-nerd/better-python-programming-for-data-scientists-part-3-data-structures-eaee8c033c1c">Data Structures</a> | Object-Oriented Programming 1 | Object-Oriented Programming 2 | Parallelization | Strategies and Tools | Books</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=355f4287f103" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-data-nerd/better-python-programming-for-data-scientists-part-4-introduction-to-object-oriented-programming-355f4287f103">Better Python Programming for Data Scientists, Part 4: Introduction to Object-Oriented Programming</a> was originally published in <a href="https://medium.com/the-data-nerd">The Data Nerd</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Strategies for Imbalanced Classes]]></title>
            <link>https://medium.com/the-data-nerd/strategies-for-imbalanced-classes-f3d8bbab3a0b?source=rss-8ce2e316e1b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3d8bbab3a0b</guid>
            <category><![CDATA[machine-learning-ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Emily Strong]]></dc:creator>
            <pubDate>Fri, 15 Jul 2022 01:40:32 GMT</pubDate>
            <atom:updated>2023-09-01T16:00:43.618Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3P3GJT_qvsPDWzgg-J6MFg.png" /><figcaption>Imbalanced Classes</figcaption></figure><p>Many real-world problems involve imbalanced classes, but most classification algorithms don’t handle them well out of the box. Sometimes they may even completely fail to predict any instances of the less common class.</p><p>So how can we approach these problems?</p><h3>1. Use a custom threshold</h3><p>One of the simplest strategies is to use a custom probability threshold for the under-represented class. For binary models, the default is typically 0.5 but this is rarely an appropriate threshold for rare classes. Setting a custom threshold is easy to accomplish with a Precision-Recall Curve. With this metric, precision and recall are calculated for different probability thresholds. You can then select the threshold value that gives acceptable metric values for the target class, or meets some other business criteria (such as the top X% of predictions).</p><p>For all of the other techniques that follow, they are frequently used in combination with custom thresholds.</p><h3>2. Oversample the smaller class(es)</h3><p>Increasing the frequency of the smaller class in the data set is another simple strategy. There are a variety of techniques available for oversampling, but two key ones to understand are:</p><ol><li>Random oversampling: a naive approach in which random instances of the class are duplicated. This can lead to overfitting.</li><li>Synthetic Minority Oversampling Technique (SMOTE): new data points are created by leveraging nearest neighbors. This algorithm takes a data point and its nearest neighbor, and creates a point that lies on the line between them. Disadvantages of SMOTE include the fact that the neighbors are chosen blindly, and they can increase the noise in the data.</li></ol><p>Several variations of SMOTE exist based on KMeans, SVM, the adaptive synthetic algorithm and other advanced strategies. For Python, they are available in the <a href="https://github.com/scikit-learn-contrib/imbalanced-learn">imbalanced-learn library</a>.</p><h3>3. Undersample the larger class(es)</h3><p>As with oversampling, there are a few basic approaches to undersampling the classes that have more data:</p><ol><li>Random undersampling: random instances are dropped from the data set. This can be done with or without replacement (bootstrapping). This approach risks losing information.</li><li>Near Misses (keep approach): uses nearest neighbors to prioritize the data points that are closest to the underrepresented class instances and are thus harder to learn.</li><li>Tomek Links (delete approach): identifies pairs of nearest neighbors that belong to different classes and removes the one from the larger class.</li><li>One-Sided Selection (OSS): combines keep and delete approaches to remove ambiguous examples as well as ones that are too far away to be useful.</li></ol><p>Machine Learning Mastery has a <a href="https://machinelearningmastery.com/undersampling-algorithms-for-imbalanced-classification/">thorough overview</a> of the specific techniques that I recommend if you want to learn more.</p><h3>4. Data augmentation and synthetic data</h3><p>SMOTE is a synthetic data technique, however there are other approaches that are worth highlighting that did not originate as oversampling algorithms. These approaches include:</p><ol><li>If the distribution of the data is known or can easily be modeled, the distribution can be used to generate new examples.</li><li>Using GANs and variational autoencoders to generate data.</li><li>The image augmentation techniques common in computer vision problems such as rotating images, adding noise, and cropping.</li></ol><h3>5. Class weighting</h3><p>Some classification algorithms support class weighting. This involves giving more weight to the underrepresented class in calculating the loss function or split purity for decision trees. Common weighting schemes include balanced weighting, in which the weight is proportionate to the inverse of the class frequency, or providing a custom mapping of {class: weight}.</p><h3>6. Use different metrics</h3><p>Accuracy and ROC Curves are common classification metrics, but they can be misleading when used with imbalanced classes. For example, if a model is predicting 100% of the data to belong to the larger class, and the smaller class only has a 2% frequency, that would give you 98% overall accuracy despite having 0% recall.</p><p>The Area Under the Precision Recall Curve (AUCPR) and F1 score give better representations of model performance for imbalanced classes. AUCPR is more sensitive to changes in the false positive rate than the ROC curve AUC, and F1 score is the harmonic mean of precision and recall.</p><h3>7. Use custom metrics</h3><p>In some cases you may want to create a custom metric that weights the classes differently or provides some custom combination of metrics appropriate to the specific use case. As an example, this Kaggle competition on <a href="https://www.kaggle.com/competitions/amex-default-prediction/overview/evaluation">predicting credit defaults</a> uses a custom metric for ranking customers based on their likelihood of defaulting based on a combination of normalized Gini coefficient and the recall in the top 4% of predictions (similar to the custom threshold approach previously mentioned).</p><h3>Conclusion</h3><p>As with machine learning algorithms in general, there is no one best strategy for imbalanced data. They each have their advantages and disadvantages. You will have to experiment to determine which ones give the best results for your data set and very often you will end up using a combination of them.</p><p>Imbalanced classes and other key concepts for working with models in real-world settings are covered in my Machine Learning Flashcards: Modeling Core Concepts deck. <a href="https://www.etsy.com/listing/1240380186/machine-learning-flashcards-modeling">Check it out on Etsy</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3d8bbab3a0b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-data-nerd/strategies-for-imbalanced-classes-f3d8bbab3a0b">Strategies for Imbalanced Classes</a> was originally published in <a href="https://medium.com/the-data-nerd">The Data Nerd</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ML Core Concepts: Precision and Recall]]></title>
            <link>https://medium.com/the-data-nerd/ml-core-concepts-precision-and-recall-4f1c27e06550?source=rss-8ce2e316e1b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f1c27e06550</guid>
            <category><![CDATA[ml-core-concepts]]></category>
            <category><![CDATA[100daysofmlcode]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Emily Strong]]></dc:creator>
            <pubDate>Mon, 11 Jul 2022 15:36:29 GMT</pubDate>
            <atom:updated>2022-07-11T15:36:29.978Z</atom:updated>
            <content:encoded><![CDATA[<p>At every data science job interview I have ever had, from grad school internships to senior data scientist roles, I have been asked to define precision and recall.</p><p>The question is a perennial job interview favorite because these two classification metrics are so commonly used in industry. They are easy for business users to grasp and are agnostic to the particulars of the use case. Even working on recommender systems, we use a slight variation in the form of Precision@K and Recall@K.</p><p>So, how do we define these two terms?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VZOTysMBB6jVuFiJJjk6NQ.png" /><figcaption>Retrieved and relevant elements</figcaption></figure><p>Consider the above visualization. We have a field of <strong>relevant </strong>items and irrelevant items, and the model <strong>retrieves</strong> some of both (the true positives and false positives). The irrelevant items that were retrieved are false positives, or <strong>Type I errors</strong>.The relevant items that were not retrieved are false negatives, or <strong>Type II errors</strong>.</p><p><strong>Recall</strong> measures how good of a job the model does at identifying all of the actual positive items. Another way to phrase that is, of all of the positives, how many of them are predicted as positive by the model. It is also known as <strong>sensitivity </strong>or <strong>true positive rate</strong>, or how sensitive the model is to the true positives. In our visualization of retrieved versus relevant items, this is the proportion of <strong>relevant</strong> items that are <strong>retrieved</strong>, or TP/(TP + FN).</p><p><strong>Precision </strong>measures how good of a job the model does at identifying only true positives. In other words, how many of the positive predictions are correct. This is also known as the <strong>positive predictive value</strong>. In our visualization above, this how many retrieved items are relevant, or TP/(TP + FP).</p><p>A closely related concept is <strong>specificity</strong>, which is the <strong>true negative rate</strong>. When both Type I and Type II errors are low, the recall, precision and specificity are high.</p><p>There are times, when you might have a very low precision and high recall, or vice versa. A useful metric when this occurs is the <strong>F1 score</strong>. This is known as the <strong>harmonic mean </strong>of precision and recall and reflects the overall accuracy of the model. It is calculated as:</p><pre>2 x (Precision x Recall) / (Precision + Recall) </pre><p>or</p><pre>2 TP / (2TP + FP + FN)</pre><p>Having one metric be low while the other is high often occurs when dealing with imbalanced classes and anomaly detection. Because it gives a more holistic picture of the model performance, F1 score is often used as an alternative to accuracy in combination with precision and recall.</p><p>Classification metrics and other key concepts for working with models in real-world settings are covered in my Machine Learning Flashcards: Modeling Core Concepts deck. <a href="https://www.etsy.com/listing/1240380186/machine-learning-flashcards-modeling">Check it out on Etsy</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f1c27e06550" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-data-nerd/ml-core-concepts-precision-and-recall-4f1c27e06550">ML Core Concepts: Precision and Recall</a> was originally published in <a href="https://medium.com/the-data-nerd">The Data Nerd</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Better Python Programming for Data Scientists, Part 3: Data Structures]]></title>
            <link>https://medium.com/the-data-nerd/better-python-programming-for-data-scientists-part-3-data-structures-eaee8c033c1c?source=rss-8ce2e316e1b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/eaee8c033c1c</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[100daysofmlcode]]></category>
            <category><![CDATA[data-sicence]]></category>
            <dc:creator><![CDATA[Emily Strong]]></dc:creator>
            <pubDate>Fri, 08 Jul 2022 14:24:44 GMT</pubDate>
            <atom:updated>2022-07-16T03:25:10.478Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Data structures header with graph example" src="https://cdn-images-1.medium.com/max/1024/1*QsZchMl5q6cAwas4qY98nw.png" /></figure><p>In <a href="https://medium.com/the-data-nerd/better-python-programming-for-data-scientists-part-1-python-fundamentals-5b76bc7d9000">Parts 1</a> and <a href="https://medium.com/the-data-nerd/better-python-programming-for-data-scientists-part-2-more-python-fundamentals-6ba076b65c0e">2</a> of this series, we explored Python fundamentals, including the built-in data types.</p><p>In part 3, we are going to look at data structures. A data structure is a collection of data elements organized in a particular format that supports basic operations for accessing those elements. Some of the Python built-in data types like lists, tuples, sets, and dictionaries are data structures, as are the commonly used Pandas data frames and series, and Numpy arrays.</p><p>In this post we are going to look at the broader spectrum of data structures used in computer science and how they are implemented in Python. You’ll see how the data structures commonly used in data science fit into the bigger picture. There are other, more advanced data structures not covered here. For those, I refer you to the Geeks For Geeks <a href="https://www.geeksforgeeks.org/advanced-data-structures/)">overview of the subject</a>.</p><p>As you learn about data structures, one thing to keep in mind is the difference between a data structure and an abstract data type. A data structure is a specific format used to store data. An abstract data type is a mathematical model that has particular behavior and properties and can be implemented by data structures, or in some cases by the simpler built-in data types such as integers.</p><h3>Array</h3><p>An array is an indexed sequence of values that all have the same data type. These elements are stored in adjacent memory locations and consist of an (index, element) tuple. Because each element is the same data type (for example a 32-bit integer), the amount of memory required for each element is known in advance and the memory location can be calculated as start location + index * memory size. In many programming languages, the size and data type of an array must be specified when it is created in order to allocate the correct amount of adjacent memory locations. When all of the memory is used, depending on the implementation the array may be dynamically resized by copying it to a new, larger array.</p><p>As you have probably guessed, Numpy’s array data structure is implemented as the standard CS array. Pandas series are also arrays with labeled axes, and an “object” data type if they contain mixed data.</p><p>Arrays are also very similar to Python lists, but they are not exactly the same since a list does not require all of the elements to have the same data type. Under the hood, lists are implemented as an array of pointers to memory locations that contain the actual elements, which is how it supports multiple data types. Laurent Luce, one of the creators of Python, provides an explanation of how this works <a href="http://www.laurentluce.com/posts/python-list-implementation/">here</a> if you want to read more about it.</p><p>Array operations:</p><ul><li><strong>Traverse</strong>: iterate through the array element by element.</li><li><strong>Insert</strong>: add a new element at the given index.</li><li><strong>Delete</strong>: remove the element at the given index.</li><li><strong>Search</strong>: find the element by index or the index by the element value.</li><li><strong>Update</strong>: modify the element at the given index.</li></ul><p>Because arrays are stored in adjacent memory locations, accessing the elements in an array by index (sometimes called <strong>peeking</strong>) is a constant-time operation.</p><p>However, this requirement for adjacent locations is a drawback of the data structure if the array is large.</p><h3>Linked List</h3><p>Linked lists solve the problem of memory allocation by storing the location of the next element in the list with the current one. That is, a linked list is a sequence of <strong>nodes</strong> consisting of (element, next location) pairs. The <strong>head</strong>, or location of the first node, is explicitly stored as a property of the linked list, and the last node has Null as the next location. Since the location of an item cannot be calculated by index, the elements cannot be directly accessed by index as in an array. Instead, the linked list must be traversed until the target element is reached (or in the case of insertion, the last node is reached) unless the location of the node is already known. However, there is no limit on the size of a linked list, no need to specify the size in advance, and no need to copy data to resize it.</p><p>A linked list has the same operations as an array, but with some differences in implementation:</p><ul><li><strong>Traverse</strong>: iterate through the linked list starting at the head and accessing each node based on the location pointer stored in the previous one.</li><li><strong>Insert</strong>: nodes can be added at the beginning by changing the stored head and pointing to the previous head in the new node. Alternatively, they can be added at the end by pointing the last node to the new one, or in the middle by swapping the stored locations as shown in the example below.</li><li><strong>Delete</strong>: nodes can be removed through the inversion of the insert operations.</li><li><strong>Search </strong>and<strong> Update</strong>: the nodes must be traversed to find the target element.</li></ul><p>Here we have an example linked list implementation with insert operations:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7088bc32f2ed3edc6d3f501d54bbcbca/href">https://medium.com/media/7088bc32f2ed3edc6d3f501d54bbcbca/href</a></iframe><p>If you find the syntax confusing, remember that when an object is stored in a variable (like self.head), the variable is actually storing a pointer to the object’s memory location. Here we are not overwriting objects, we are just changing the location pointer.</p><p>A <strong>doubly linked list</strong> addresses some of the inefficiency of a linked list by storing both the previous and next locations so that the list can be traversed in either direction.</p><p>Arrays and linked lists serve as core data structures that other data structures are implemented with.</p><h3>Bag</h3><p>A bag is an unordered collection to which new elements can be added but existing ones cannot be removed. They allow duplicates, and because of this are sometimes called multisets. The collection can be traversed, and individual elements accessed by searching.</p><p>To understand the concept behind this data structure, consider the example of a running standard deviation calculation. A running mean can be computed without storing individual values since you just need to update their sum and quantity to calculate the current mean. However, a running standard deviation requires storing the values since for each of them the difference between the value and the current mean must be calculated. We don’t want to remove any of these values at any point, and we don’t care about their order, we just need to store them and be able to iterate over them.</p><p>Bags can be implemented with arrays or linked lists.</p><h3>Stacks and Queues</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EvE5aVxusoU9Ay0dbDvTfg.png" /><figcaption>The Last In First Out process for a stack</figcaption></figure><p>A stack is an ordered collection to which elements can be added and removed following a <strong>Last In First Out (LIFO)</strong> ordering. That is, the most recently added item is operated on first, like a stack of plates in the cupboard. The two key operations of a stack are:</p><ul><li><strong>Push</strong>: add a new item to the top of the stack.</li><li><strong>Pop</strong>: remove an item from the top of the stack.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*A3FgWz7rEtAn9jTbL6ViaA.png" /><figcaption>The First In First Out process for a queue</figcaption></figure><p>A queue is an ordered collection in which items are added and removed in <strong>a First In First Out (FIFO)</strong> ordering. That is, items are removed in the order in which they were added, like how lines (at least in theory) work in real life. The operations for a queue are:</p><ul><li><strong>Push</strong>: add a new item to the back of the queue.</li><li><strong>Pop</strong>: remove the item from the front of the queue</li></ul><p>Stacks and queues are linear and can be implemented with either arrays or linked lists. They are also available in the Python collections module through the deque (“deck”) class. This is a left-to-right ordered generalized implementation that can push or pop from either direction.</p><p>Here we have an example of working with the deque class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a80653a767a4b4ff436486e508ce7a33/href">https://medium.com/media/a80653a767a4b4ff436486e508ce7a33/href</a></iframe><h3>Binary Tree</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ooChIQRYH6AoNku4F_BiaA.png" /><figcaption>Different types of binary trees</figcaption></figure><p>A binary tree is a tree in which each <strong>node</strong> has at most two <strong>child</strong> nodes (usually called the left and right child). In concept, they are somewhat similar to a doubly linked list in that they have as properties the data of the node and two pointers, one to each child. Some of the key concepts for binary trees are:</p><ul><li><strong>Root</strong>: the top-level node that does not have a parent node.</li><li><strong>Leaf</strong>: a terminal node.</li><li><strong>Depth/height, h</strong>: how many levels the tree has. A tree consisting of a root with no leaves has a height of 0.</li><li><strong>Full</strong>: a tree in which every node has either 0 or 2 child nodes. A full tree has at least 2h + 1 nodes and at most 2^(h+1) -1.</li><li><strong>Perfect</strong>: a tree in which every interior node has 2 children and all leaves are at the same depth/level.</li><li><strong>Complete</strong>: a tree in which every level except the last is full, and the last-level nodes are all as far to the left as possible; a perfect tree is complete but a complete tree does not have to be perfect or full</li><li><strong>Balanced</strong>: the left and right branches of every node differ in height by at most 1</li><li><strong>Degenerate</strong>: every parent has at most 1 child.</li></ul><p>The operations of a tree are:</p><ul><li><strong>Traversal</strong>: this can be depth-first (going all the way to the terminal leaf of a branch before visiting the next branch) or breadth-first (visiting the closest nodes first).</li><li><strong>Insertion</strong>: new nodes can easily be inserted as a child of a leaf, or as an internal by updating the pointers of the existing nodes.</li><li><strong>Deletion</strong>: a node with no children can easily be deleted, and if it has one child, the child can become a child of the removed node’s parent. Depending on the implementation, algorithms exist for rearranging the tree if a deleted node has two children.</li></ul><p>For implementation, binary trees can be created either with a node class and pointer variables similar to our linked list example, or they can be implemented as an array in breadth-first order. In this implementation, the node at index i<em> </em>has children at 2i + 1 and<em> </em>2i + 2, while its parent is at floor((i-1)/2). A breadth-first array is more compact since the pointers to the child nodes are calculated rather than explicitly stored, but it is more expensive to grow and can waste space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*WDjDgVsrnZuqK8_cAgOMSA.png" /><figcaption>A breadth-first array implementation of a binary tree</figcaption></figure><p>Just as arrays and linked lists underlie more complex linear data structures, binary trees are used to implement non-linear ones.</p><h3>Binary Search Tree</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sj9BvdWpGwEbTnFqwAo9rQ.png" /><figcaption>A binary search tree</figcaption></figure><p>Binary Search Trees (BSTs) are a special type of binary tree. They are ordered so that at each internal node, the values in the left branch are less than the node value, and the values in the right branch are greater than the node value. This data structure is useful for fast search and information retrieval because the time complexity is O(h). How well it performs depends on how balanced the tree is, but on average operations performed with a BST are O(log n).</p><p>A BST that automatically keeps its height optimal when items are inserted or deleted is known as a <strong>self-balancing binary search tree</strong>.</p><h3>Heap</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*-HktPG2o8QuwuM7Zcy9erw.png" /><figcaption>The heapify process for a max-heap</figcaption></figure><p>Heaps are another special type of binary tree. There are two types: <strong>min-heaps </strong>and <strong>max-heaps</strong>. Like BSTs, these are sorted trees, but each node is either greater than (for max-heap) or less than (for min-heap) its child values. This property is recursive throughout the tree. Insertion and deletion operations require maintaining the ordering by swapping values until order has been restored in a process known as <strong>heapify</strong>.</p><p>Heaps are complete binary trees and can be implemented as breadth-first arrays. They are used to implement <strong>priority queues</strong>, in which the “priority” of the element based on its value rather than insertion order determines the sequence in which it leaves the queue. Unlike BSTs, heaps do not guarantee that everything on one side of the tree will be greater than or less than everything on the other side, the recursive ordering applies along the full depth of a branch from root to leaf. The priority ordering means that the min or max of the collection of values can be identified in constant time.</p><p>Binary trees, BSTs and heaps are not included in the Python standard library but there are various libraries you can install to leverage them if you don’t want to implement the data structures yourself.</p><h3>Hash Table</h3><p>A hash table, also known as a <strong>dictionary</strong>, is a data structure in which a hash function is used to compute an index for a <strong>bucket</strong> to store a key-value pair.</p><p>If you’re thinking, <em>Wait a minute, a</em> <em>dictionary</em>… That’s right! We finally have a data structure that is one of the Python built-in data types. Additionally, Pandas data frames can be thought of as dictionaries of series (labeled arrays).</p><p>Because the index for a pair is computed from the key, there is the chance that two different keys could yield the same hash value. This is known as a <strong>collision</strong>, and there are two main strategies for handling it:</p><ul><li><strong>Separate chaining</strong>: each index contains a pointer to a linked list (or a self-balancing BST for ordered storage). As collisions happen, the new items are added to the linked list, which must be traversed to find an individual key-value pair when the pair needs to be accessed.</li><li><strong>Open addressing</strong>: each index contains a pointer to the actual element. When a collision happens, a sequence is followed to find the next open slot in a process known as <strong>probing</strong>. For example, in a linear probe the interval between slots to check is fixed, and usually 1.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NbUZRssViK9D7rSnnIZvIg.png" /><figcaption>Separate Chaining versus Open Addressing with a linear probe</figcaption></figure><p>Open addressing is more compact than separate chaining, but as the example above shows, can be inefficient for finding elements if there are many collisions.</p><p>Aside from the built-in dictionary data type, hash tables can also be used in machine learning algorithms such as locality sensitive hashing, which is used to group similar items and is one algorithm for Approximate Nearest Neighbors problems. You can see an example use of this for multi-armed bandits in the MABWiser library (<a href="https://fidelity.github.io/mabwiser/api.html#mabwiser.mab.NeighborhoodPolicy.LSHNearest">documentation</a>, <a href="https://github.com/fidelity/mabwiser/blob/master/mabwiser/approximate.py">source code</a>). It can also be used in natural language processing for use cases like identifying similar word embeddings for translation or entire web pages for filtering pages that are too similar from search results.</p><h4>A Note on Associative Arrays</h4><p>An associative array is the more general abstract data type also known as a <strong>map</strong>, a <strong>symbol table</strong>, or a <strong>dictionary</strong>. They store key-value pairs, and under the hood can be implemented with hash tables, linked lists, or binary trees, with hash tables being the most common. As previously mentioned, Python 3.6+ uses a hash table for its dictionary data type. If you want to learn more, the <a href="https://en.wikipedia.org/wiki/Associative_array">Wikipedia article on it</a> provides a thorough overview of the different implementation methods.</p><h3>Matrix and Sparse Matrix</h3><p>When referring to a matrix as a data structure, it is a special type of two-dimensional array, or an array of arrays, that is noteworthy as the elements must all be the same size. That is, each array within the array represents either a row with the same number of columns (row-major order), or a column with the same number of rows (column-major order).</p><p>Sparse matrices, however, represent a unique problem. Because arrays are a fixed size with the memory allocated at creation, they can be very inefficient for sparse data. Various solutions involving other data structures have been developed to solve this:</p><ul><li><strong>Dictionary of keys (DOK)</strong>: each key is a (row, column) pair.</li><li><strong>List of lists (LIL)</strong>: each row is a sorted list of column index and value pairs.</li><li><strong>Coordinate list (COO)</strong>: a sorted list in which each element is a (row, column, value) tuple, ordered by row then column.</li><li><strong>Compressed sparse row (CSR)</strong>: three one-dimensional arrays store the values, the corresponding column indices of those values, and the starting and ending slice indices for the row data in the value and column arrays.</li><li><strong>Compressed sparse column (CSC)</strong>: similar to CSR but tracks column slice indices rather than rows.</li></ul><p>To give an example of the CSR format, consider the matrix:</p><pre>[[ 1, 0, 0, 0]</pre><pre>[0, 0, 2, 0,]</pre><pre>[3, 4, 0, 0]]</pre><p>We would have the arrays:</p><ul><li>values = [1, 2, 3, 4]</li><li>column_index= [0, 2, 0, 1]</li><li>row_index = [0, 1, 2, 4]</li></ul><p>This translate to row 1 is values[0:1] and column_index[0:1], row 2 is values[1:2] and column_index[1:2], and row 3 is values[2:3] and column_index[2:4]. This format is faster for accessing the row data and performing calculations. Scipy provides <a href="https://docs.scipy.org/doc/scipy/reference/sparse.html">implementations</a> of each of these formats, but scikit-learn classes that return sparse matrices such as the TF-IDF Vectorizer default to using the CSR format.</p><h3>Graphs</h3><p>The last stop on our tour of data structures is the graph. Graphs are both abstract data types and data structures. They consist of a set of <strong>vertices</strong> or <strong>nodes</strong> and the <strong>edges</strong> that connect them. Edges represent the relationships between nodes, and they can be <strong>directed</strong> or <strong>undirected</strong>. Edges can have a value, called the <strong>cost </strong>or<strong> weight</strong>, associated with them.</p><p>When using a graph to represent data, often (though certainly not always) they can be conceptualized as the nodes capturing the nouns of the data while the edges are the verbs. For example, in the graph of a social network website, each person would be a node. An undirected edge might represent a mutual relationship such as being friends or some other reciprocal connection, and a directed edge might represent following or subscribing to a person’s posts. That is A --&gt; B translates to “A follows B”.</p><p>Another common example for graphs is the game of Six Degrees of Kevin Bacon (<a href="https://en.wikipedia.org/wiki/Six_Degrees_of_Kevin_Bacon">https://en.wikipedia.org/wiki/Six_Degrees_of_Kevin_Bacon</a>). In this game, a random Hollywood celebrity is selected, and through films they have acted in, directed, or produced (our directed edges) they can be connected to Kevin Bacon through up to 5 other celebrity-nodes (where Kevin Bacon is the 6th node in the “6 degrees).</p><p>The primary operations of a graph data structure is to report the list of neighbors of a vertex as well as any stored properties such as the cost and directionality.</p><p>There are three types of data structures commonly used to implement graphs:</p><ul><li><strong>Adjacency list</strong>: each vertex is stored as an object that contains a list of adjacent vertices. Additional data can be stored in the object as well. If edges are also objects, they can store additional data as well, and each vertex contains a list of edges while each edge contains a pair of vertices. Specific implementations include an array of linked lists or a hash table.</li><li><strong>Adjacency matrix</strong>: a two-dimensional matrix where the rows are source vertices and columns are destination vertices. Any additional data must be externally stored. The value stored can be the cost of the edge. The cost or directionality can be stored as the value in the matrix, with -1 for leaving and 1 for entering.</li><li><strong>Incidence matrix</strong>: a two-dimensional matrix where the rows are vertices and the columns are edges. The cost or directionality can be stored as the value in the matrix, with -1 for leaving and 1 for entering.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kPpxhMaqtWrB3F_cqi45jA.png" /><figcaption>An undirected graph</figcaption></figure><p>If we consider the above undirected graph, these representations would be:</p><p><em>Adjacency list</em></p><pre>0: {1, 3, 4}</pre><pre>1: {0}</pre><pre>2: {4, 5}</pre><pre>3: {0, 4}</pre><pre>4: {0, 2, 3, 5}</pre><pre>5: {2, 4}</pre><p><em>Adjacency matrix</em></p><pre>Node 0  1  2  3  4  5</pre><pre>0    0  1  0  1  1  0</pre><pre>1    1  0  0  0  0  0</pre><pre>2    0  0  0  0  1  1</pre><pre>3    1  0  0  0  1  0 </pre><pre>4    1  0  1  1  0  1</pre><pre>5    0  0  1  0  1  0</pre><p>Note the symmetry of the adjacency matrix for an undirected graph.</p><p><em>Incidence matrix</em></p><pre>Node E1 E2 E3 E4 E5 E6 E7</pre><pre>0    1  1  1  0  0  0  0</pre><pre>1    1  0  0  0  0  0  0</pre><pre>2    0  0  0  0  1  0  1</pre><pre>3    0  1  0  1  0  0  0</pre><pre>4    0  0  1  1  1  1  0</pre><pre>5    0  0  0  0  0  1  1</pre><p>Which data structure representation is best depends on how densely connected the network is and what data needs to be stored with the relationships. Adjacency lists are often used for sparse graphs, while adjacency matrices are often used for dense ones. As we can see in the example above for an incidence matrix the number of columns grows with the number of edges making it less suitable for a dense graph, while for a sparse graph there would be the inefficiency of a sparse matrix.</p><p>Knowledge graphs have recently emerged as a useful way of organizing information for machine learning. Check out <a href="http://ai.stanford.edu/blog/introduction-to-knowledge-graphs/">this post</a> from the Standford AI Lab blog for an introduction to the subject.</p><p>Graphs are not directly available in standard Python, but data structures such as an adjacency list or matrix are simple to implement and graph databases such as <a href="https://neo4j.com/">Neo4j</a> have Python APIs.</p><h3>Conclusion</h3><p>Data structures is one of the subjects that is foundational in computer science but is easy to skip if you enter data science from another field. However, if you need to write a lot of custom functionality such as creating a library or a complex pipeline, choosing the right data structures for the problem can make your code simpler and more efficient. This post has given an overview of the fundamental data structures you would learn about in an undergraduate computer science course.</p><p>If you want to learn more about these data structures and their use in algorithms, the <a href="https://algs4.cs.princeton.edu/home/">book site for <em>Algorithms</em></a><em> </em>by Robert Sedgewick and Kevin Wayne contains a condensed version of the text that is an excellent resource and the corresponding course is available for free on Coursera (<a href="https://www.coursera.org/learn/algorithms-part1">Part 1</a> | <a href="https://www.coursera.org/learn/algorithms-part2">Part 2</a>). The book and course use Java but figuring out how to implement the data structures and algorithms in Python from the Java examples is a good exercise to help you master them.</p><p>Stay tuned for the rest of the Better Python Programming for Data Scientists series!</p><p><a href="https://medium.com/the-data-nerd/better-python-programming-for-data-scientists-part-1-python-fundamentals-5b76bc7d9000">Python Fundamentals</a> | <a href="https://medium.com/the-data-nerd/better-python-programming-for-data-scientists-part-2-more-python-fundamentals-6ba076b65c0e">More Python Fundamentals</a> | Data Structures | <a href="https://medium.com/@thedatanerd/better-python-programming-for-data-scientists-part-4-introduction-to-object-oriented-programming-355f4287f103">Object-Oriented Programming 1 </a>| Object-Oriented Programming 2 | Parallelization | Strategies and Tools | Books</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eaee8c033c1c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-data-nerd/better-python-programming-for-data-scientists-part-3-data-structures-eaee8c033c1c">Better Python Programming for Data Scientists, Part 3: Data Structures</a> was originally published in <a href="https://medium.com/the-data-nerd">The Data Nerd</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Homoscedasticity vs Heteroscedastcity]]></title>
            <link>https://medium.com/the-data-nerd/homoscedasticity-vs-heteroscedastcity-366e8b21d79?source=rss-8ce2e316e1b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/366e8b21d79</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[100daysofmlwriting]]></category>
            <category><![CDATA[100daysofmlcode]]></category>
            <dc:creator><![CDATA[Emily Strong]]></dc:creator>
            <pubDate>Sat, 02 Jul 2022 15:24:04 GMT</pubDate>
            <atom:updated>2022-07-02T15:28:05.112Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Homoscedacity and Heteroscedacity plots" src="https://cdn-images-1.medium.com/max/1024/1*XnZoCu1w3ssCBMB-iLBWKg.png" /><figcaption>Plots of data with homogeneous and heterogenous variance. Adapted from shorturl.at/mqvLM and shorturl.at/iDKNX.</figcaption></figure><p>Homoscedasticity is constant (or homogeneous) variance in a set of random variables. You may be wondering how it’s possible for variance to change. Isn’t it a single number?</p><p>This is where the idea of a set of variables factors in. We are not looking at a single variable in isolation, we are looking at the relationship between a combination of variables. For example, your dependent variable has actual and predicted values. When talking about the variance in this set, we are referring to the variance of the predicted values (or their error) as a function of the actual value.</p><p>One of the fundamental assumptions of <a href="https://medium.com/the-data-nerd/day-1-linear-regression-4816a039a5fa">linear regression</a> is that the error in the predictions is homoscedastic. When this assumption is violated, measures of goodness of fit are no longer reliable. Homoscedacity is also required for anaysis of variance (ANOVA) tests.</p><p>Heteroscedacity, as you may have guessed, is heterogeneous variance. This is a common characteristic of many real-world relationships. For example, if you consider the relationship between income and how much money people spend on food, those who have higher incomes will have greater flexibility of choice in how much they spend. Some may spend more on luxury ingredients or dining out while others may have simpler, more frugal habits, leading to a high variance. Those with less income on the other hand will have much more limited budgets and less variance.</p><p>You can test for heteroscedacity for linear regression with the Breusch-Pagan test, which checks for dependence between the variance in errors and the independent variables. This test is available in Python in the statsmodel package.</p><p>If any of your independent variables do have heteroscedacity, you can still use them with linear models by applying a correction:</p><ol><li>Convert the individual feature to a log scale</li><li>Convert the target to a log scale or other appropriate transformation</li><li>Apply weights to the training data in <a href="https://en.wikipedia.org/wiki/Weighted_least_squares">weighted least squares</a> estimation</li><li>Use <a href="https://en.wikipedia.org/wiki/Heteroskedasticity-consistent_standard_errors">heteroscedasticity-consistent standard error</a> (HCSE) estimation</li></ol><p>These alternatives to ordinary least squares estimation are available in the statsmodel package, which also has a thorough <a href="https://www.statsmodels.org/devel/examples/notebooks/generated/wls.html">tutorial on WLS.</a></p><p>Homoscedacity, heteroscedacity and other key concepts for working with models in real-world settings are covered in my Machine Learning Flashcards: Modeling Core Concepts deck. <a href="https://www.etsy.com/listing/1240380186/machine-learning-flashcards-modeling">Check it out on Etsy</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=366e8b21d79" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-data-nerd/homoscedasticity-vs-heteroscedastcity-366e8b21d79">Homoscedasticity vs Heteroscedastcity</a> was originally published in <a href="https://medium.com/the-data-nerd">The Data Nerd</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Bias-Variance Tradeoff]]></title>
            <link>https://medium.com/the-data-nerd/understanding-the-bias-variance-tradeoff-78bcce4062f1?source=rss-8ce2e316e1b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/78bcce4062f1</guid>
            <category><![CDATA[100daysofmlcode]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[100daysofmlwriting]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Emily Strong]]></dc:creator>
            <pubDate>Thu, 30 Jun 2022 21:15:28 GMT</pubDate>
            <atom:updated>2022-06-30T21:15:28.581Z</atom:updated>
            <content:encoded><![CDATA[<p>The Bias-Variance Tradeoff is a concept that is easy to skip over when first starting out in machine learning, and yet it’s one of the most fundamental principles of the field (and is an interview-question favorite).</p><p>To understand this tradeoff, we first need to understand model error.</p><p>Every machine learning model has error. (If your model doesn’t have any errors it’s actually a very bad sign of <a href="https://machinelearningmastery.com/data-leakage-machine-learning/">data leakage</a>.) The test data error has three components to it:</p><ol><li><strong>Noise</strong>: The random noise intrinsic to the data set.</li><li><strong>Bias</strong>: Systematic errors due to the simplifying assumptions of the model.</li><li><strong>Variance</strong>: How much the predictions vary between models trained on different samples of the training data.</li></ol><p>The noise of the data is model independent and will always contribute to the total error.</p><p>Bias on the other hand is directly related to the algorithm used, though all machine learning algorithms have it. This is easy to conceptualize for <a href="https://medium.com/the-data-nerd/day-1-linear-regression-4816a039a5fa">linear regression</a>, in which there is a fundamental assumption of a linear relationship between the features and the target variable. However, many features do not have a linear relationship and unless an appropriate transformation is applied (e.g. converting to a log scale), the linear regression will <strong>underfit</strong> those features as a result. Underfitting is the failure to learn the relationship between features and target.</p><p>Other more complex algorithms have simplifying assumptions as well. For a decision tree, this often occurs from the hyperparameters such as setting a minimum number of data points per leaf, or setting a maximum depth. These hyperparameters improve how well the model <strong>generalizes </strong>to new data, but they do so by simplifying the model. A random forest adds further simplifications to the trees within it through sampling. Each tree is trained on a bootstrapped sample of the data, and each split point can only consider a sample of the features. By having less data available for the individual trees and split points, we have a simpler model that generalizes better, but has more bias. Additionally, any use of regularization simplifies a model by constraining the parameters which increases the bias. A <a href="https://medium.com/the-data-nerd/day-2-ridge-regression-3fab52ca9fd">ridge regression</a> thus has greater bias than a linear regression.</p><p>Variance represents the interaction between the data and the algorithm in the error. Any algorithm trained on a different sample of the training data will learn a different model, whether it is the values of parameters, or the data itself in a non-parametric model. However some algorithms will have greater sensitivity to fluctuations in the data and tend to <strong>overfit</strong>, learning the noise of the data instead of generalizing.</p><p>In the graph below, we can see the concepts of overfitting and underfitting illustrated. In this example, we have two classes with a parabolic decision boundary between them. Some of the data points don’t perfectly align with this boundary, falling on the wrong side of it.</p><figure><img alt="Overfitting and underfitting" src="https://cdn-images-1.medium.com/max/500/1*bNqo3Hss1HfgefzAl7ci1Q.png" /><figcaption>Adapted from: <a href="https://en.wikipedia.org/wiki/Overfitting#/media/File:Overfitting.svg">https://en.wikipedia.org/wiki/Overfitting#/media/File:Overfitting.svg</a></figcaption></figure><p>An optimal model that generalizes well will learn the parabola despite the slight variations in some of the data.</p><p>An overfit model, that is one with high variance, will learn to map every single data point, resulting in a roughly-parabolic squiggle. With a slightly different sample of data, the shape of this squiggly line would change, and when attempting to make predictions about the test data, the ones that fall along the decision boundary will likely have a higher error rate due to the poor generalization.</p><p>An underfit model, one with high bias, will learn the relationship it is designed to assume regardless of the actual shape of the decision boundary, resulting in a straight line that poorly fits the data.</p><p>A common metaphor for thinking about bias and variance is how well the test predictions hit the accuracy bullseye. A low bias, low variance model will be tightly clustered around the center with a high accuracy. Increasing the variance increases the spread of the predictions (that is, the same test data will have variations in their predictions from different models). Increasing the bias on the other hand shifts the clustering of the predictions off-center. When we have both high variance and high bias, the model performs quite poorly.</p><p>In the bullseye visualization below, we would say that the high variance low bias model is overfitting, while the high bias low variance model is underfitting, and the high variance high bias model is just plain bad.</p><figure><img alt="Bias versus variance bullseye" src="https://cdn-images-1.medium.com/max/860/1*3BnGaboA_0ZoNnGmlbRgpw.png" /><figcaption>Image credit: <a href="http://scott.fortmann-roe.com/docs/BiasVariance.html">http://scott.fortmann-roe.com/docs/BiasVariance.html</a></figcaption></figure><p>The concepts of bias and variance come together to give us the Bias-Variance Tradeoff. This is the idea that as model complexity increases so does the variance, while the bias decreases. We can plot this as the relation between model complexity and model error:</p><figure><img alt="Diagram of model complexity vs error" src="https://cdn-images-1.medium.com/max/459/1*zEiCjRPyPXBHGSyor8Ln1w.png" /><figcaption>Image credit: <a href="http://scott.fortmann-roe.com/docs/BiasVariance.html">http://scott.fortmann-roe.com/docs/BiasVariance.html</a></figcaption></figure><p>The total error of the model is the sum of the variance, the square of the bias, and the error due to noise. At the extreme high and low ends of model complexity we have high total error due to the high variance or high bias. The goal of selecting the optimal model for a problem is to find one that minimizes the total error.</p><p>In real-world settings, high variance models are rarely used directly because of their tendency to overfit. Instead, we use them as the individual learners within boosting and bagging algorithms that reduce the variance (and increase the bias) to give much lower total error. However, high bias models like logistic or ridge regression are common. Why is that?</p><p>For a few reasons: first, the simplifying assumptions make them faster to train. Second, their predictions are easier to interpret and explain. Third, they are more robust to variance when there isn’t a lot of data available for initial training, particularly if the regularization strength is high. And finally, they are more robust to drift in the data over time. These considerations can make high bias models useful in practice, though they do still need to have acceptable performance.</p><p>The Bias-Variance Tradeoff is thus a useful concept to factor into what algorithms you consider when tackling a problem.</p><p>The Bias-Variance Tradeoff and other key concepts for working with models in real-world settings are covered in my Machine Learning Flashcards: Modeling Core Concepts deck. <a href="https://www.etsy.com/listing/1240380186/machine-learning-flashcards-modeling">Check it out on Etsy</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78bcce4062f1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-data-nerd/understanding-the-bias-variance-tradeoff-78bcce4062f1">Understanding the Bias-Variance Tradeoff</a> was originally published in <a href="https://medium.com/the-data-nerd">The Data Nerd</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Better Python Programming for Data Scientists, Part 2: More Python Fundamentals]]></title>
            <link>https://medium.com/the-data-nerd/better-python-programming-for-data-scientists-part-2-more-python-fundamentals-6ba076b65c0e?source=rss-8ce2e316e1b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ba076b65c0e</guid>
            <category><![CDATA[100daysofmlcode]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[100daysofmlwriting]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Emily Strong]]></dc:creator>
            <pubDate>Tue, 28 Jun 2022 19:09:38 GMT</pubDate>
            <atom:updated>2022-07-16T03:24:49.764Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*A5oFe6pdL7-wDfbjNyDddg.png" /><figcaption>An animal emoji printer with conditional logic</figcaption></figure><p>In <a href="https://medium.com/the-data-nerd/better-python-programming-for-data-scientists-part-1-python-fundamentals-5b76bc7d9000">Part 1</a> of this series, we started our dive into Python fundamentals by looking at the different Python implementations available and the built-in data types. With that foundation, we can now look at some of the fundamentals of coding in Python.</p><p>The topics covered in this post are actually fundamentals of coding in general, but I’ve found that a lot of junior data scientists don’t use them, or don’t use them enough, and we’ll focus specifically on their implementations in Python.</p><h3>Functions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*YNH0_dODpSp55rg0-f6DLw.png" /><figcaption>Example Python function</figcaption></figure><p>Any time you repeat code while programming, there is potentially the opportunity to convert that code into a function. Functions increase the modularity and reusability of code (and any tool that decreases the amount of work you have to do is a positive). They can also make it easier to read and follow the logic.</p><p>As a data scientist, you use various functions from various libraries every day, but unless you <em>create</em> them regularly, you may not have needed to think about how functions are put together in a while. A function has four basic components: a name, a parameter list, a body (this is the code that gets reused), and a return data type which can be None if the function doesn’t return anything. Optionally, you can provide default values for the arguments, and provide a docstring. You can also include type hints as discussed in Part 1. These components come together as follows:</p><pre>def function_name(parameter1, parameter2=DefaultValue):<br>    &#39;&#39;&#39;docstring&#39;&#39;&#39;<br>    some code<br>    return DataType</pre><p>If the function doesn’t return anything, you can omit the return statement, you can explicitly return None, or you can have the word return followed by nothing (called an empty return statement) if you find that easier to read.</p><h4>Docstrings</h4><p>An important aspect of functions that I want to highlight is docstrings. Though technically optional, providing docstrings for your functions is a very good habit to be in. When sharing code with others or revisiting your own code after some time away from it, docstrings can simplify the process of understanding what the code does as a higher level than individual in-line comments.</p><p>At a minimum, docstrings provide explanations of what each function is, but they can also provide descriptions of the parameters and what is returned, detailed explanations of how the function works, and example code (which some IDEs can run as doctests). If you ever plan to create documentation for a module or library, there are tools you can use such as <a href="https://www.sphinx-doc.org/">Sphinx</a> to automatically generate it from the docstrings. As an example, compare the documentation for the scikit-learn implementation of <a href="https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.Ridge.html#sklearn.linear_model.Ridge">Ridge Regression</a> to the docstring in the <a href="https://github.com/scikit-learn/scikit-learn/blob/80598905e/sklearn/linear_model/_ridge.py#L910">source code</a>.</p><p>This <a href="https://stackoverflow.com/a/24385103">Stack Overflow answer</a> provides an overview of the different docstring formats that are commonly used in Python. I’m partial to the Numpy format, which is compatible with Sphinx.</p><h3>Iteration</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*HIrbueiDRReMtFEjvRbNZQ.png" /><figcaption>Iteration with zipping</figcaption></figure><p>Iteration is the process of repeating an action on successive items in a sequence. Here, sequence is used in the general sense, not referring specifically to sequence data types.</p><p>In Python, an <strong>iterator</strong> is an object that contains a countable number of values or elements that is created when you apply iteration to an <strong>iterable</strong> object — a container that can return its elements one by one — such as a list, string (which is a list of characters), dictionary, or data frame. You can create one by calling the iter() function on the object that contains the target sequence. The function that performs the traversal of the iterator is next(). Python’s built-in iterable data types and many others have this implemented for you so that you never need to write for example iter_object = iter(list_object) to create the iterator of a list, though if you try to call next() on these data types it will raise a type error. You may never need to directly use iter() and next(), but they are worth knowing about to understand how iteration is implemented under the hood in Python.</p><p>More commonly, you will simply use a for or while loop.</p><ul><li>Python’s <strong>for </strong>loops are an implementation of the more general idea of a <strong>foreach</strong> loop in which the entire sequence of items is traversed. They do not require having an end condition defined though you can have logic within the loop that causes it to end.</li><li>Python’s <strong>while</strong> loops traverse the sequence so long as a condition remains true. It can optionally be used with an <strong>else</strong> statement that runs when the condition is no longer true.</li></ul><p>Iteration is such a fundamental and useful process, Python has a few tricks you can use to avoid having to write out common uses:</p><ul><li><strong>Zipping</strong>: the zip() function aggregates iterables to pair up their elements. The resulting zip object contains tuples of corresponding items from each iterable, with the length determined by the shortest iterable. For example if you zip the lists [1, 2, 3, 4] and [‘a’, ‘b’, ‘c’, ‘d’] you get [(1, ‘a’), (2, ‘b’), (3, ‘c’), (4, ‘d’)]. If the first list were instead [1, 2, 3, 4, 5, 6], you would get the same result since the last two elements don’t have corresponding items in the second list.</li><li><strong>Enumerate</strong>: the enumerate()function is a special type of zipping that aggregates a counter with the object being iterated over, so that each tuple in the sequence consists of the count value and the next element from the iterable object. If you have ever used the Pandas iterrows function, this is the same idea as the index, row pairs.</li><li><strong>List comprehension</strong>: this is a shortcut for creating a new list from an existing one by applying a function or condition to each element in a single line of code. The syntax is new_list = [func(x) for x in old_list if condition], with the function call and condition both optional depending on your needs.</li></ul><p>At this point, you may be wondering: When do you need a function versus iteration for repeated operations?</p><p>A loop can of course call a function within it, and a function can contain a loop, but the usefulness of a function is when you are writing (or copying and pasting) code multiple times. If the code is only written once within a single for loop, a function probably isn’t necessary for most use cases though you can choose to use one for stylistic reasons.</p><p>Under-utilization of for loops and custom functions are the most frequent opportunities for improving data science code that I see. They significantly enhance readability, and reduce logic errors and reproducibility problems by eliminating the mistakes that are easy to make when reusing code such as forgetting to change a variable name.</p><h3>Generators and Yield</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*q4UtQgtXEnhfI7f_sGdsXw.png" /><figcaption>An example generator expression</figcaption></figure><p>A<strong> generator function</strong> is a special type of function that behaves like an iterator but does not store its contents in memory. An example is the readline() function used to iterate over the lines of a file. Generators can be particularly useful to reduce memory requirements when working with large amounts of data.</p><p>To create a generator function, the syntax is the same as regular functions but they use the <strong>yield</strong> keyword instead of <strong>return</strong>. The difference between the two is that any code placed after a return statement is not executed, while a yield pauses to output a value then resumes with the existing states of all variables retained.</p><p>You can also create <strong>generator expressions</strong>, which similarly create generator objects but can be written as a single line like a list comprehension. They have the form:</p><pre>generator_expression= (func(x) for x in iterable_object)</pre><p>The iterable object can be a file, as with a generator function.</p><p>You may never need to create your own generators, but because of their applications in working with files and big data, knowing about them will help you understand the tools you are working with.</p><h3>Lambdas</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*bGn-ELw4zD-QjytBx_OHuQ.png" /><figcaption>An example lambda function</figcaption></figure><p>Lambdas are simple <strong>anonymous functions</strong>, though they may call other functions with more complex functionality. They are created with the syntax:</p><pre>lambda arguments: expression</pre><p>Since they don’t require a full function definition, they can be stored as a variable or used without being stored.</p><p>Lambdas can be used by being passed as an argument to another function such as a list comprehension or Pandas apply() for applying it to the rows or columns of a data frame. A few functions that you may not have encountered before but can be useful when working with lambdas are:</p><ul><li><strong>Map</strong>: returns an iterator that applies the lambda expression to every element of an iterable object.</li><li><strong>Accumulate</strong>: returns an iterator that applies an aggregation lambda function (such as sum or max) to an iterable object.</li><li><strong>Filter</strong>: returns an iterator that filters the elements of an iterable object to only those that meet a condition.</li></ul><p>Alternatively, a lambda can have arguments passed to it directly in the form:</p><pre>(lambda function)(argument value)</pre><p>For example (lambda x: x**2)(4)returns 16. This syntax is useful for things like parallelization which we will be covering in a later post.</p><p>For a more in-depth look at lambdas in Python and additional examples, check out this <a href="https://www.geeksforgeeks.org/python-lambda-anonymous-functions-filter-map-reduce/">Geeks for Geeks article</a>.</p><h3>Conditional Logic</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*Dy72dGeOQzR7kb0LcBNsdQ.png" /><figcaption>Our animal emoji printer implemented with pattern matching for Python 3.10</figcaption></figure><p>The basic conditional logic in Python are the <strong>if/elif/else</strong> statements. These are standard Boolean conditions with <strong>and/or/not</strong> operators for compound expressions. If statements can be used without requiring an elif or else. That is, nothing happens when the if statement is false. Python also supports the <strong>ternary operator</strong>:</p><pre>expression if condition else expression</pre><p>This is for cases where there is only one condition to evaluate, though you can have a nested ternary in the else expression.</p><p>For <strong>switch statements</strong>, an option has been <a href="https://peps.python.org/pep-0636/">added in Python 3.10</a> called <strong>pattern matching</strong>, but for older versions of Python you need to either use a block of if/elif/else statements or a dictionary that has lambdas or functions as the values. The newly available syntax follows the standard switch statement pattern:</p><pre>match subject:<br>    case value/pattern:<br>        code<br>    case value/pattern:<br>        code<br>    case _:<br>        default code</pre><p>The underscore character condition in this example is a wildcard that always returns true if reached and is optional. It is intended for things like raising exceptions.</p><p>There are three additional statements that can be useful in control logic:</p><ul><li><strong>Pass</strong>: This is equivalent to “do nothing”. If you have some conditions that don’t require their own special operations performed under an if/elif branch but you want to exclude them from the default behavior of the else statement, you can use pass. This keyword is described in more detail in the next section.</li><li><strong>Continue</strong>: This is used within a loop and indicates that the rest of the logic in the loop should be skipped for this particular iteration, but the loop should not end. For example, if iterating through a list looking for a particular element, you might have something happen when that element is found, otherwise continue.</li><li><strong>Break</strong>: This indicates that the loop should end. If the loop occurs in a function, you can instead use return.</li></ul><h3>The Pass Keyword</h3><p>When working on a complex project, you may want to plan out the steps of what you need to do with placeholder code before you are ready to implement it. This helps you stay organized and identify what’s left to be done. I often use placeholders as a dynamic To Do List when writing functions or creating case logic. However, you also often want to test portions of the project code as you go to make sure they work correctly and having unimplemented sections of code would raise a syntax error. Similarly, you may encounter cases where some portion of your code needs to be temporarily commented out but doing so would cause an error.</p><p>To avoid this, you can use the keyword <strong>pass</strong>. Pass does nothing but is a complete statement so that you won’t have errors from empty functions, for loops, and branches in control logic. You can use it on its own, or to replace commented out logic.</p><p>The pass keyword is also useful in production code for certain use cases including in object-oriented programming, which we will cover in a later post in this series, and in APIs where executable code can be passed as an argument, known as a callback. (If you’ve been paying attention, that should sound familiar from our discussion of lambdas. Lambdas can be passed as callbacks, as can named functions and classes.)</p><h3>Modules</h3><p>A Python module is a file that contains function and variable definitions that can be imported into other Python files (scripts, modules, notebooks). The module name for importing is the file name without the .py extension. You can make a module independently executable by adding at the end:</p><pre>if __name__ == “__main__”:<br>    some code that uses the functions and variables</pre><p>A single module can be used as a catch-all for any functions and variables you want to reuse, but it is easy for them to become unwieldy as your code base grows. If you are working on a large, complex project you may want to organize your code into separate modules and directories.</p><h3>Putting it All Together</h3><p>There is a lot of basic functionality available in Python that you can use to make your programming more efficient and scalable. Examples of how I use these capabilities in my everyday work include:</p><ul><li>Dynamically generating SQL queries.</li><li>Generating tabular features from text and other unstructured or semi-structured data.</li><li>Using iteration anywhere that an operation needs to be repeated for multiple objects or values.</li><li>Working with config files.</li><li>Taking steps that I commonly perform in EDA and wrapping them in functions.</li><li>Moving functions to a module so that I don’t have to copy and paste code over and over between notebooks.</li><li>Creating pipelines to run experiments rather than using notebooks.</li></ul><p>This is by no means an exhaustive list. As you go through the articles in this series, you’ll spot many other opportunities to leverage the fundamentals of Python to improve your programming.</p><p>Stay tuned for the rest of the Better Python Programming for Data Scientists series!</p><p><a href="https://medium.com/the-data-nerd/better-python-programming-for-data-scientists-part-1-python-fundamentals-5b76bc7d9000">Python Fundamentals</a> | More Python Fundamentals | <a href="https://medium.com/the-data-nerd/better-python-programming-for-data-scientists-part-3-data-structures-eaee8c033c1c">Data Structures</a> | <a href="https://medium.com/@thedatanerd/better-python-programming-for-data-scientists-part-4-introduction-to-object-oriented-programming-355f4287f103">Object-Oriented Programming 1</a> | Object-Oriented Programming 2 | Parallelization | Strategies and Tools | Books</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ba076b65c0e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-data-nerd/better-python-programming-for-data-scientists-part-2-more-python-fundamentals-6ba076b65c0e">Better Python Programming for Data Scientists, Part 2: More Python Fundamentals</a> was originally published in <a href="https://medium.com/the-data-nerd">The Data Nerd</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Introduction to Uplift Modeling]]></title>
            <link>https://medium.com/the-data-nerd/an-introduction-to-uplift-modeling-737d0d78e3e?source=rss-8ce2e316e1b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/737d0d78e3e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[100daysofmlcode]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[100daysofmlwriting]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Emily Strong]]></dc:creator>
            <pubDate>Wed, 22 Jun 2022 21:07:39 GMT</pubDate>
            <atom:updated>2022-06-22T21:07:39.155Z</atom:updated>
            <content:encoded><![CDATA[<p>Marketing campaigns can be expensive. You want to contact only the people who you think will be persuaded to do whatever it is your campaign is about — buying something, donating money, voting, etc. If they were already going to do it, or never will, contacting them is a waste of resources. Worse, there are some people who would have done it on their own, but being contacted causes them to change their mind!</p><p>We need a model that can isolate only the people who are persuadable to optimize the return on our investment in the campaign.</p><p>This is where uplift modeling comes in. An uplift model predicts the incremental impact of a <strong>treatment</strong> (being contacted) on an individual when compared to if they were <strong>untreated </strong>in the <strong>control</strong> group. Uplift modeling is a form of causal modeling in which we attempt to isolate the effect of being treated on a person’s behavior. This experiment enables us to determine the true lift in the target variable that is attributable to the treatment. It is also sometimes called true lift modeling or incremental modeling.</p><p>This approach divides the people who are eligible to be contacted into four behavior segments:</p><ol><li><strong>Sure things</strong>: the folks who would do the thing regardless of whether or not you contact them.</li><li><strong>Persuadables</strong>: the folks who will only do the thing if contacted.</li><li><strong>Lost Causes</strong>: the folks who will never do the thing regardless of whether you contact them.</li><li><strong>Do Not Disturbs</strong>: the folks who will be dissuaded from doing the thing because you contacted them. Also called <strong>Sleeping Dogs </strong>(as in “don’t wake a sleeping dog”).</li></ol><figure><img alt="Uplift model behavior segments" src="https://cdn-images-1.medium.com/max/1024/1*W2qd2sV6FWikAxgyCEtcRg.png" /><figcaption>Behavior Segments in an Uplift Model</figcaption></figure><p>There are algorithms specifically designed for uplift modeling available in the CausalML library, however you can also use simple classification models with one of these techniques:</p><ol><li>Train separate models on the treatment and control groups. At inference, generate predictions from each model for the individual and calculate the difference in the target variable. This difference is the lift attributable to treatment.</li><li>Assign a treatment indicator as one of the model features. At inference, generate predictions both with and without the indicator and calculate the difference.</li><li>Assign people to the 4 behavior segments and train a multi-class classifier to predict which segment someone belongs to.</li></ol><p>The use of uplift modeling can significantly improve the return on investment for a marketing campaign, both by avoiding wasting time and resources on contacting people who are sure things, and by decreasing the risk of triggering someone in the “Do Not Disturb” group from changing their mind.</p><p>Uplift modeling and other key concepts for working with models in real-world settings are covered in my Machine Learning Flashcards: Modeling Core Concepts deck. <a href="https://www.etsy.com/listing/1240380186/machine-learning-flashcards-modeling">Check it out on Etsy</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=737d0d78e3e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-data-nerd/an-introduction-to-uplift-modeling-737d0d78e3e">An Introduction to Uplift Modeling</a> was originally published in <a href="https://medium.com/the-data-nerd">The Data Nerd</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Model Uncertainty]]></title>
            <link>https://medium.com/the-data-nerd/understanding-model-uncertainty-3d8250a9ea1a?source=rss-8ce2e316e1b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d8250a9ea1a</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[100daysofmlwriting]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Emily Strong]]></dc:creator>
            <pubDate>Tue, 21 Jun 2022 15:54:40 GMT</pubDate>
            <atom:updated>2022-06-21T15:54:40.596Z</atom:updated>
            <content:encoded><![CDATA[<p>Every model has uncertainty. The model learns from imperfect or incomplete information, which impacts decisions about the “best” algorithm, hyperparameters, and features.</p><p>This fundamental uncertainty has three sources:</p><ol><li>Assumptions inherent to the algorithm. No algorithm can perfectly model a real-world problem, there is always some error due to the fact that the model learns generalizations.</li><li>Noise in the data. Every real-world data set always has some degree of randomness. This leads to what we call <strong>aleatoric uncertainty</strong>, or <strong>statistical uncertainty</strong>.</li><li>Some things are knowable but may not be represented in the training data due to incomplete coverage of the problem domain. This leads to <strong>epistemic uncertainty.</strong></li></ol><p>While the assumptions made by a model are algorithm-specific, the latter two sources of uncertainty relate to the data. We can look at some examples to gain a better understanding of them.</p><h3>Aleatoric Uncertainty</h3><figure><img alt="Street where a building’s shadow covers part of the street" src="https://cdn-images-1.medium.com/max/1024/0*pXpyYmznUhOilv3R" /><figcaption>Photo by <a href="https://unsplash.com/@jamesgarmandotcom?utm_source=medium&amp;utm_medium=referral">James Garman</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Aleatoric uncertainty stems from noise in the data. There is always some amount of randomness in any real-world data set.</p><p>Even in a carefully controlled scientific experiment, data is collected through indirect measurement — that is, the measurement is taken using equipment. This equipment has a level of imprecision, as well as potential sources of error, and the thing being measured often cannot be completely isolated. If you’ve ever seen <em>Breaking Bad</em>, think of how Walter White is proud of 99.1% purity. Even he can’t achieve 100% purity; it’s impossible. Similarly, in physics there is the particle-wave duality of light — whether light behaves like a particle or a wave depends on how it is being observed. These indirect measurements lead to noise.</p><p>Outside of scientific experiments, an easy example to consider is the photo above depicting a sidewalk-lined street partially covered by a building’s shadow. The shadow creates a distinct straight edge in the road while reducing the contrast at the boundary between sidewalk and street. This adds noise to the image. If a model were attempting to segment the photo, it may detect the shadow as an edge and incorrectly bound the street even though to a human eye we can easily see the actual boundary.</p><p>For any data set, there is noise from errors in measurement as well as from inherent randomness. In something as seemingly straightforward as a house sale price, although a bank will use a specific formula for calculating the <em>value</em>, there are human factors external to the physical properties of the house that can add noise to the final negotiated price. For an NLP problem, we may have noise from the errors people make when speaking and writing such as using the wrong word or making a grammar mistake, but there will also be noise stemming from the fact that two people saying the same thing will likely phrase it slightly differently.</p><p>Although a sufficiently large data set should provide coverage of the range of values that is possible within the domain, the inherent noise will always add uncertainty to the model.</p><h3>Epistemic Uncertainty</h3><p>Beyond the noise in the data, we have uncertainty from the fact that training data is always a sample. It will never be all of the data (if it were, you wouldn’t have new data to make predictions for). This gives us epistemic uncertainty, the uncertainty derived from what we don’t know but could learn.</p><p>As you may have guessed, using more data reduces epistemic uncertainty. It cannot be completely eliminated since there will always be more data to observe, but we factor it into our model evaluation by using holdout test data or cross validation, and reinforcement learning or model retraining can further reduce it over time.</p><h3>Conclusion</h3><p>Model uncertainty can be a challenging concept to grasp, especially when first starting out in data science. We want there to be a correct answer, a correct model, but because of fundamental uncertainty, the correct model doesn’t exist. The sources of uncertainty are thus important to consider when we evaluate performance and in determining how to use the outputs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d8250a9ea1a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-data-nerd/understanding-model-uncertainty-3d8250a9ea1a">Understanding Model Uncertainty</a> was originally published in <a href="https://medium.com/the-data-nerd">The Data Nerd</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>