<?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 Vincent Favilla on Medium]]></title>
        <description><![CDATA[Stories by Vincent Favilla on Medium]]></description>
        <link>https://medium.com/@vincefav?source=rss-b7798f9bcb53------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gwklGBXZg-yrwxyNAMuXfA.jpeg</url>
            <title>Stories by Vincent Favilla on Medium</title>
            <link>https://medium.com/@vincefav?source=rss-b7798f9bcb53------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 06:25:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vincefav/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[Code an AI Assistant with GPT Function Calls]]></title>
            <link>https://medium.com/@vincefav/code-an-ai-assistant-with-gpt-function-calls-adbf63c46918?source=rss-b7798f9bcb53------2</link>
            <guid isPermaLink="false">https://medium.com/p/adbf63c46918</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[gpt-4]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Vincent Favilla]]></dc:creator>
            <pubDate>Thu, 15 Jun 2023 01:55:04 GMT</pubDate>
            <atom:updated>2023-06-15T02:37:40.165Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LiXTy5VlVxhScxxOh7e8-g.png" /></figure><p>OpenAI’s GPT series now supports <a href="https://openai.com/blog/function-calling-and-other-api-updates">function calling</a>, a powerful feature that allows developers to get structured data from the model by describing functions to it. This is a game-changer in the world of AI development, as it gives the AI model the ability to work with tools, extending its capabilities beyond just generating text.</p><h3>Why is Function Calling Useful?</h3><p>Imagine you’re building a chatbot. Without function calling, the chatbot can answer questions based on the information it was trained on. But what if a user asks a question that requires real-time data, like the current weather or stock market prices? Or what if the user wants to perform an action, like booking a hotel room or sending an email?</p><p>This is where function calling comes in. By describing your custom functions to GPT, you’re giving it the ability to interact with your code. The model can then generate a JSON object containing arguments to call your functions.</p><p>This means your chatbot can now fetch real-time data or perform actions based on user requests. Here are some ways you can use function calling:</p><ul><li><strong>Create interactive chatbots</strong>: Your chatbot can now perform actions like booking a hotel room, sending an email, or fetching real-time data based on user requests.</li><li><strong>Convert natural language into API calls</strong>: You can convert user requests like “Who are my top customers?” into API calls to your backend.</li><li><strong>Extract structured data from text</strong>: You can define a function to extract all people mentioned in a Wikipedia article, for example.</li><li><strong>Automated Data Analysis</strong>: Suppose you have a function that can analyze a dataset and provide insights, such as identifying trends, outliers, or making predictions. With function calling, you can have a user ask the AI in natural language to analyze a specific dataset and the AI can call your function to perform the analysis and return the results.</li><li><strong>E-commerce</strong>: If you’re running an e-commerce platform, you can define functions for actions like adding items to a cart, applying discount codes, or checking out. The AI can then call these functions based on user requests, providing a conversational shopping experience.</li><li><strong>Educational Tools</strong>: For an educational application, you could define functions that generate quiz questions, provide hints, or evaluate answers. The AI can interact with these functions to provide an interactive learning experience.</li><li><strong>Healthcare Applications</strong>: In a healthcare setting, you could define functions that pull up patient records, schedule appointments, or provide medical advice based on symptoms. The AI can call these functions to assist healthcare professionals or patients. (Remember, any sensitive data should be handled within your local functions and not included in the conversation with the model to ensure privacy and compliance with regulations like HIPAA.)</li><li><strong>Interactive Gaming</strong>: In a game, you could define functions that control the player’s actions, like moving in a certain direction, attacking, or using an item. The AI can call these functions based on the player’s natural language commands, creating a unique, voice-controlled gaming experience.</li></ul><p>In essence, function calling allows you to create more interactive and useful AI applications by bridging the gap between the AI model and your custom code.</p><p>Let’s demo this new functionality with a simple but useful example: let’s give GPT the ability to perform arithmetic, since we know that math is a weakness of large language models.</p><p>I’ll adapt the code from the OpenAI function calls cookbook, and add a bit more commentary so you can follow along.</p><h3>Setup</h3><p>The first step is to install and import the required libraries:</p><pre>pip install openai tenacity termcolor requests json</pre><p>Then import the libraries and set your GPT model and API key:</p><pre>import json<br>import openai<br>import requests<br><br># For retrying an API call if it fails<br>from tenacity import retry, wait_random_exponential, stop_after_attempt<br><br># For color coding a conversation<br>from termcolor import colored<br><br>GPT_MODEL = &quot;gpt-3.5-turbo-0613&quot;<br>openai.api_key = &quot;YOUR_API_KEY&quot;</pre><p>Now let’s define some helper functions. You can keep these the same in any project you create.</p><p>First, a function to send API requests:</p><pre>@retry(wait=wait_random_exponential(min=1, max=40), stop=stop_after_attempt(3))<br>def chat_completion_request(messages, functions=None, function_call=None, model=GPT_MODEL):<br>    &quot;&quot;&quot;<br>    This function sends a POST request to the OpenAI API to generate a <br>    chat completion.<br>    Parameters:<br>    - messages (list): A list of message objects. Each object should have a<br>      &#39;role&#39; (either &#39;system&#39;, &#39;user&#39;, &#39;function&#39;, or &#39;assistant&#39;)<br>       and &#39;content&#39; (the content of the message).<br>    - functions (list, optional): A list of function objects that describe the functions that the model can call.<br>    - function_call (str or dict, optional): If it&#39;s a string, it can be either &#39;auto&#39; (the model decides whether to call a function) or &#39;none&#39; <br>      (the model will not call a function). If it&#39;s a dict, it should describe the function to call.<br>    - model (str): The ID of the model to use.<br>    Returns:<br>    - response (requests.Response): The response from the OpenAI API. If the request was successful, the response&#39;s JSON will contain the chat completion.<br>    &quot;&quot;&quot;<br>    # Set up the headers for the API request<br>    headers = {<br>        &quot;Content-Type&quot;: &quot;application/json&quot;,<br>        &quot;Authorization&quot;: &quot;Bearer &quot; + openai.api_key,<br>    }<br>    # Set up the data for the API request<br>    json_data = {&quot;model&quot;: model, &quot;messages&quot;: messages}<br>    # If functions were provided, add them to the data<br>    if functions is not None:<br>        json_data.update({&quot;functions&quot;: functions})<br>    # If a function call was specified, add it to the data<br>    if function_call is not None:<br>        json_data.update({&quot;function_call&quot;: function_call})<br>    # Send the API request<br>    try:<br>        response = requests.post(<br>            &quot;https://api.openai.com/v1/chat/completions&quot;,<br>            headers=headers,<br>            json=json_data,<br>        )<br>        return response<br>    except Exception as e:<br>        print(&quot;Unable to generate ChatCompletion response&quot;)<br>        print(f&quot;Exception: {e}&quot;)<br>        return e</pre><p>As of the time I’m writing this, function calling does not seem to be supported in the Python API, so we have to use POST requests instead. The function above will simplify that process considerably.</p><p>Next we can use a function to color-code a conversation, making it easier to read:</p><pre># This function supplied by OpenAI doesn&#39;t work in Colab; I have an alternative function for this in the next cell<br><br>def original_pretty_print_conversation(messages):<br>    &quot;&quot;&quot;<br>    This function takes a list of messages as input. <br>    Each message is a dictionary with a `role` and `content`.<br>    The `role` can be &quot;system&quot;, &quot;user&quot;, &quot;assistant&quot;, or &quot;function&quot;. <br>    This function formats each message based on its role <br>    and appends it to the `formatted_messages` list. <br>    Finally, it prints each formatted message in a color corresponding <br>    to its role.<br>    &quot;&quot;&quot;<br><br>    # Define a dictionary to map roles to colors<br>    role_to_color = {<br>        &quot;system&quot;: &quot;red&quot;,<br>        &quot;user&quot;: &quot;green&quot;,<br>        &quot;assistant&quot;: &quot;blue&quot;,<br>        &quot;function&quot;: &quot;magenta&quot;,<br>    }<br><br>    # Initialize an empty list to store the formatted messages<br>    formatted_messages = []<br><br>    # Iterate over each message in the messages list<br>    for message in messages:<br>        # Check the role of the message and format it accordingly<br>        if message[&quot;role&quot;] == &quot;system&quot;:<br>            formatted_messages.append(f&quot;system: {message[&#39;content&#39;]}\n&quot;)<br>        elif message[&quot;role&quot;] == &quot;user&quot;:<br>            formatted_messages.append(f&quot;user: {message[&#39;content&#39;]}\n&quot;)<br>        elif message[&quot;role&quot;] == &quot;assistant&quot; and message.get(&quot;function_call&quot;):<br>            formatted_messages.append(f&quot;assistant: {message[&#39;function_call&#39;]}\n&quot;)<br>        elif message[&quot;role&quot;] == &quot;assistant&quot; and not message.get(&quot;function_call&quot;):<br>            formatted_messages.append(f&quot;assistant: {message[&#39;content&#39;]}\n&quot;)<br>        elif message[&quot;role&quot;] == &quot;function&quot;:<br>            formatted_messages.append(f&quot;function ({message[&#39;name&#39;]}): {message[&#39;content&#39;]}\n&quot;)<br><br>    # Print each formatted message in its corresponding color<br>    for formatted_message in formatted_messages:<br>        print(<br>            colored(<br>                formatted_message,<br>                role_to_color[messages[formatted_messages.index(formatted_message)][&quot;role&quot;]],<br>            )<br>        )</pre><p><em>Note that this method of formatting text doesn’t work in Google Colab, but my accompanying </em><a href="https://colab.research.google.com/drive/18etCkTvGS0Qwx9qSRl26G8kCI5wIx8LS?usp=sharing"><em>notebook</em></a><em> has another function you can use instead.</em></p><p>Now let’s define a function for GPT to use:</p><pre>def add_numbers(num1, num2):<br>    return num1 + num2</pre><p>Simple enough, right? But now we need to write a JSON specification to explain the function to GPT:</p><pre>functions = [<br>    {<br>        &quot;name&quot;: &quot;add_numbers&quot;,<br>        &quot;description&quot;: &quot;Add two numbers&quot;,<br>        &quot;parameters&quot;: {<br>            &quot;type&quot;: &quot;object&quot;,<br>            &quot;properties&quot;: {<br>                &quot;num1&quot;: {<br>                    &quot;type&quot;: &quot;number&quot;,<br>                    &quot;description&quot;: &quot;The first number&quot;,<br>                },<br>                &quot;num2&quot;: {<br>                    &quot;type&quot;: &quot;number&quot;,<br>                    &quot;description&quot;: &quot;The second number&quot;,<br>                },<br>            },<br>            &quot;required&quot;: [&quot;num1&quot;, &quot;num2&quot;],<br>        },<br>    },<br>]</pre><p>A few things to note here:</p><ul><li>This data is what GPT sees — not your Python function. So it’s up to you to clearly describe your variables and what your function does.</li><li>You’re probably going to be using more than one function, but they all go inside here since they get converted to JSON and sent with your requests.</li><li>GPT is actually really good at writing these specifications itself! So give it an example and show it your functions and it should be able to help you write these properly.</li><li>The “type” here is “number” (and not “float”) because JSON schema uses “number” to represent both integers and floating-point numbers.</li></ul><p>Next we’ll need a way to call the functions that GPT requests to use. A simple way to do this is to have a dictionary that maps function names as strings back to the original functions:</p><pre>functions_dict = {<br>    &quot;add_numbers&quot;: add_numbers,<br>}</pre><p>Finally, let’s start a conversation with GPT:</p><pre>messages = []<br>messages.append({&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a helpful assistant.&quot;})</pre><h3>Using Your New Functions</h3><p>This functionality won’t be all that helpful unless it can work with ambiguous user requests. So rather than giving it a math quiz, let’s see if it can figure out for itself when to use the tools it has:</p><pre>messages.append(<br>  {<br>  &quot;role&quot;: &quot;user&quot;,<br>  &quot;content&quot;: &quot;I have a bill for $323 and another for $295. How much do I owe?&quot;<br>  }<br>)</pre><p>Now we generate a response using our chat function:</p><pre># Generate a response<br>chat_response = chat_completion_request(<br>    messages, functions=functions<br>)<br><br># Save the JSON to a variable<br>assistant_message = chat_response.json()[&quot;choices&quot;][0][&quot;message&quot;]<br><br># Append response to conversation<br>messages.append(assistant_message)</pre><p>If we print the assistant_message we just got, we’ll see this:</p><pre>{&#39;role&#39;: &#39;assistant&#39;,<br> &#39;content&#39;: None,<br> &#39;function_call&#39;: {&#39;name&#39;: &#39;add_numbers&#39;,<br>  &#39;arguments&#39;: &#39;{\n  &quot;num1&quot;: 323,\n  &quot;num2&quot;: 295\n}&#39;}}</pre><p>This is GPT telling us that it’s ready to use a function rather than send a text-based response. So let’s run it!</p><pre>if assistant_message[&quot;function_call&quot;]:<br>  <br>  # Retrieve the name of the relevant function<br>  function_name = assistant_message[&quot;function_call&quot;][&quot;name&quot;] # `add_numbers`<br><br>  # Retrieve the arguments to send the function<br>  function_args = json.loads(assistant_message[&quot;function_call&quot;][&quot;arguments&quot;])<br>                                                               # 323 and 295<br><br>  # Look up the function in our dictionary and <br>  # call it with the provided arguments<br>  result = functions_dict[function_name](**function_args)<br><br>  print(result)</pre><p><em>We get back 618, which is indeed correct!</em></p><p>The next thing we need to do is add a new message to the conversation with the function result:</p><pre>messages.append({<br>    &quot;role&quot;: &quot;function&quot;,<br>    &quot;name&quot;: function_name,<br>    &quot;content&quot;: str(result),  # Convert the result to a string<br>})</pre><p>Lastly, we need to tell the user what the total was:</p><pre># Call the model again to generate a user-facing message <br># based on the function result<br>chat_response = chat_completion_request(<br>    messages, functions=functions<br>)<br>assistant_message = chat_response.json()[&quot;choices&quot;][0][&quot;message&quot;]<br>messages.append(assistant_message)<br><br># Print the final conversation<br>pretty_print_conversation(messages)</pre><p>We get back this:</p><pre>system: You are a helpful assistant.<br><br>user: I have a bill for $323 and another for $295. How much do I owe?<br><br>assistant: {&#39;name&#39;: &#39;add_numbers&#39;, &#39;arguments&#39;: &#39;{\n  &quot;num1&quot;: 323,\n  &quot;num2&quot;: 295\n}&#39;}<br><br>function (add_numbers): 618<br><br>assistant: You owe a total of $618.</pre><p>So the assistant is, in fact, able to report back the result with natural language. (And, for an app in production, you’ll probably elect not to display messages without content, so that the user sees only the “user” and “assistant” messages.)</p><h3>Adding More Functionality</h3><p>Of course, you’re likely to be giving GPT access to more than one function, so let’s repeat this process with another tool at its disposal: subtraction. This example will be helpful for seeing how GPT can successfully choose from an arbitrary selection of functions.</p><p>The code that follows will look familiar: we’re doing the same thing we did for our addition function to add a subtraction function.</p><pre># Define in Python<br>def subtract_numbers(num1, num2):<br>    return num1 - num2<br><br><br># Define the function specification<br># — notice we&#39;re appending this to our previous function list using +=<br>functions += [<br>    {<br>        &quot;name&quot;: &quot;subtract_numbers&quot;,<br>        &quot;description&quot;: &quot;Subtract two numbers&quot;,<br>        &quot;parameters&quot;: {<br>            &quot;type&quot;: &quot;object&quot;,<br>            &quot;properties&quot;: {<br>                &quot;num1&quot;: {<br>                    &quot;type&quot;: &quot;number&quot;,<br>                    &quot;description&quot;: &quot;The first number&quot;,<br>                },<br>                &quot;num2&quot;: {<br>                    &quot;type&quot;: &quot;number&quot;,<br>                    &quot;description&quot;: &quot;The second number&quot;,<br>                },<br>            },<br>            &quot;required&quot;: [&quot;num1&quot;, &quot;num2&quot;],<br>        },<br>    },<br>]<br><br># Add to our function dictionary<br>functions_dict[&#39;subtract_numbers&#39;] = subtract_numbers</pre><p>Now let’s try an even more ambiguous prompt to see how GPT does: “I have $8013 in my checking account. How much will I have after I pay my bills?”</p><pre>messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;I have $8013 in my checking account. How much will I have after I pay my bills?&quot;})</pre><p>And then the same code we saw before:</p><ul><li>Generate a response (which will be a request to use a function)</li><li>Append that response to the conversation</li><li>Retrieve the name of the relevant function from the JSON response</li><li>Retrieve the arguments and then look up the function and run it with those arguments</li><li>Add a new message to the conversation with the function result</li><li>Generate a user-facing message with that result</li></ul><pre># Generate a response<br>chat_response = chat_completion_request(<br>    messages, functions=functions<br>)<br>assistant_message = chat_response.json()[&quot;choices&quot;][0][&quot;message&quot;]<br><br># Append response to conversation<br>messages.append(assistant_message)<br><br># I like putting an if statement here, but it&#39;s up to you<br>if assistant_message[&quot;function_call&quot;]:<br><br>    # Retrieve the name of the relevant function<br>    function_name = assistant_message[&quot;function_call&quot;][&quot;name&quot;]<br>    <br>    # Retrieve the arguments to send the function<br>    function_args = json.loads(assistant_message[&quot;function_call&quot;][&quot;arguments&quot;])<br>    <br>    # Look up the function and call it with the provided arguments<br>    result = functions_dict[function_name](**function_args)<br>    <br>    # Add a new message to the conversation with the function result<br>    messages.append({<br>        &quot;role&quot;: &quot;function&quot;,<br>        &quot;name&quot;: function_name,<br>        &quot;content&quot;: str(result),  # Convert the result to a string<br>    })<br>    <br>    # Call the model again to generate a user-facing message <br>    # based on the function result<br>    chat_response = chat_completion_request(<br>        messages, functions=functions<br>    )<br>    assistant_message = chat_response.json()[&quot;choices&quot;][0][&quot;message&quot;]<br>    messages.append(assistant_message)<br><br>    # Print the final conversation<br>    pretty_print_conversation(messages)</pre><p>This time it’s trickier because subtraction is not commutative like addition is: it actually matters what order num1 and num2 are in. But when we print the final conversation, we see:</p><pre>system: You are a helpful assistant.<br><br>user: I have a bill for $323 and another for $295. How much do I owe?<br><br>assistant: {&#39;name&#39;: &#39;add_numbers&#39;, &#39;arguments&#39;:<br>          &#39;{\n  &quot;num1&quot;: 323,\n  &quot;num2&quot;: 295\n}&#39;}<br><br>function (add_numbers): 618<br><br>assistant: You owe a total of $618.<br><br>user: I have $8013 in my checking account. How much will I have after<br>      I pay my bills?<br><br>assistant: {&#39;name&#39;: &#39;subtract_numbers&#39;, &#39;arguments&#39;:<br>          &#39;{\n  &quot;num1&quot;: 8013,\n  &quot;num2&quot;: 618\n}&#39;}<br><br>function (subtract_numbers): 7395<br><br>assistant: After paying your bills, you will have $7395 remaining in your<br>           checking account.</pre><p>So, GPT was able to correctly infer that num1 should be 8013 and num2 should be the sum of the bills mentioned previously, 618.</p><h3>Conclusion</h3><p>This simple example does a great job of demonstrating the power and flexibility of function calling in GPT models. Even ambiguously phrased messages can be parsed correctly, and the appropriate function can be selected and executed. This opens up a world of possibilities for developers to create more interactive and useful AI applications.</p><p>Once you go through the code and try implementing your own example, you’ll find that the process is fairly straightforward. You can define any function you want, describe it to GPT, and then use it in your conversations. This opens up a world of possibilities for creating more interactive and dynamic AI applications.</p><p>OpenAI CEO Sam Altman reportedly commented that ChatGPT plug-ins don’t seem to have product-market fit. Whereas developers originally thought they wanted their app inside ChatGPT, they actually want ChatGPT inside their app. This new feature allows developers to do just that. By integrating GPT into your applications, you can leverage the power of AI to enhance user experience, automate tasks, and provide real-time data and insights.</p><p>So dig into my <a href="https://colab.research.google.com/drive/18etCkTvGS0Qwx9qSRl26G8kCI5wIx8LS?usp=sharing">Colab notebook</a> with the code for implementing function calls. We’re about to see an explosion of interesting new services, and I hope yours is one of them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adbf63c46918" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Logistic Regression in Python with StatsModels]]></title>
            <link>https://medium.com/@vincefav/mastering-logistic-regression-in-python-with-statsmodels-52bd7cc77af4?source=rss-b7798f9bcb53------2</link>
            <guid isPermaLink="false">https://medium.com/p/52bd7cc77af4</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Vincent Favilla]]></dc:creator>
            <pubDate>Sun, 04 Jun 2023 20:41:16 GMT</pubDate>
            <atom:updated>2023-06-04T20:41:16.775Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7su9nJm9DO1UHm0del3QTg.png" /></figure><p><em>View the accompanying </em><a href="https://colab.research.google.com/drive/1GwdYQn9PW_XPKErp7biz6UprL9a-oln-#scrollTo=bILX2xki9OcN"><em>Colab notebook</em></a><em>.</em></p><p>In this tutorial, we’ll explore how to perform logistic regression using the StatsModels library in Python. We’ve previously covered logistic regression using scikit-learn, but StatsModels provides more detailed statistics, which can be useful for understanding the model’s performance.</p><p>StatsModels is a Python library built specifically for statistics. It provides a wide range of statistical models, tests, and data exploration tools. In this tutorial, we will focus on using StatsModels for logistic regression.</p><h3>Importing Libraries and Datasets</h3><p>First, let’s import the necessary libraries and load the dataset. We’ll use the built-in breast cancer dataset from scikit-learn.</p><pre>import numpy as np<br>import pandas as pd<br>import statsmodels.api as sm<br>from sklearn import datasets<br>from sklearn.model_selection import train_test_split<br>from sklearn.preprocessing import StandardScaler<br><br># Load the breast cancer dataset<br>data = datasets.load_breast_cancer()</pre><h3>Preparing the Dataset</h3><p>Now, let’s prepare the dataset by splitting it into training and testing sets, removing highly correlated features, and standardizing our data.</p><pre># Split the dataset into train and test sets<br>X_train, X_test, y_train, y_test = train_test_split(<br>  X, y, test_size=0.2, random_state=42)<br><br># Standardize the data<br>scaler = StandardScaler()<br>X_train = scaler.fit_transform(X_train)<br>X_test = scaler.transform(X_test)<br><br># Remove highly correlated features<br>corr_matrix = pd.DataFrame(X_train).corr().abs()<br>upper = corr_matrix.where(np.triu(np.ones(corr_matrix.shape), k=1).astype(bool))<br>to_drop = [column for column in upper.columns if any(upper[column] &gt; 0.9)]<br><br>X_train = pd.DataFrame(X_train).drop(to_drop, axis=1)<br>X_test = pd.DataFrame(X_test).drop(to_drop, axis=1)</pre><h3>Feature Selection Techniques</h3><p>In addition to evaluating the model, you can also improve its performance and interpretability by selecting the most relevant features.</p><p>The code for recursive feature elimination and regularization is actually quite long using the statsmodels API, but you can find it in my <a href="https://colab.research.google.com/drive/1GwdYQn9PW_XPKErp7biz6UprL9a-oln-#scrollTo=bILX2xki9OcN">logistic regression Colab notebook</a>. It’s quite neat to see, and the benefit of using statsmodels over scikit-learn is that it provides more detailed statistical information about the model.</p><h3>Performing Logistic Regression with StatsModels</h3><p>Now that our dataset is prepared, we can perform logistic regression using StatsModels. First, we need to add a constant term to our features, as StatsModels does not include it by default.</p><p>The constant term, also known as the bias or intercept, allows the logistic regression model to have a non-zero output when all the input features are zero. In other words, it represents the baseline output of the model when no input features are influencing the prediction. Including a constant term in the model can improve its flexibility and ability to fit the data.</p><pre># Add a constant term to the train and test data<br>X_train = sm.add_constant(X_train)<br>X_test = sm.add_constant(X_test)<br><br># Fit the logistic regression model<br>logit_model = sm.Logit(y_train, X_train)<br>result = logit_model.fit()</pre><h3>Interpreting Results</h3><p>Once the model is fitted, we can view the summary of the results, which includes various statistics that we can use to understand our model:</p><pre># Print the summary of the results<br>print(result.summary())</pre><p>This outputs a bunch of useful information about our model. Let’s start with the header:</p><pre>Optimization terminated successfully.<br>         Current function value: 0.034995<br>         Iterations 15<br>                           Logit Regression Results                           <br>==============================================================================<br>Dep. Variable:                      y   No. Observations:                  455<br>Model:                          Logit   Df Residuals:                      434<br>Method:                           MLE   Df Model:                           20<br>Date:                Sat, 03 Jun 2023   Pseudo R-squ.:                  0.9470<br>Time:                        20:35:24   Log-Likelihood:                -15.923<br>converged:                       True   LL-Null:                       -300.17<br>Covariance Type:            nonrobust   LLR p-value:                1.233e-107</pre><p>Lots of math here! Let’s go over the table.</p><ul><li><strong>Dep. Variable</strong>: The name of the dependent variable, which is the target variable “y” in our case.</li><li><strong>Model</strong>: The type of model used, which is logistic regression (Logit) in our case.</li><li><strong>Method</strong>: The method used to fit the model, which is Maximum Likelihood Estimation (MLE) in our case.</li><li><strong>Date</strong> and <strong>Time</strong>: The date and time when the model was fitted.</li><li><strong>converged</strong>: A boolean value indicating whether the optimization algorithm has converged or not. Convergence means that the algorithm has found the best possible coefficients for our logistic regression model, and further iterations would not significantly improve the model’s performance.</li><li><strong>Covariance Type</strong>: This term refers to the technique employed for estimating the variability of the coefficients, specifically the covariance matrix of these estimated coefficients. The covariance matrix offers insights into the potential changes in the coefficients if the model were to be fitted on various data samples.<br>The term “nonrobust” in our output indicates that the default method was used, which assumes that the errors — the differences between predicted probabilities and actual target values — are independently and identically distributed (i.i.d.).<br>Note that StatsModels offers other robust covariance matrix estimators for cases where the i.i.d. assumption is not satisfied; however, for this tutorial, we will adhere to the default nonrobust method.</li><li><strong>No. Observations</strong>: The number of observations (samples) used to fit the model.</li><li><strong>Df Residuals</strong>: The degrees of freedom of the residuals, calculated as the number of observations minus the number of parameters (including the constant term). Degrees of freedom represent the number of independent pieces of information that are used to estimate the parameters of the model.</li><li><strong>Df Model</strong>: The number of parameters in the model, excluding the constant term.</li><li><strong>Pseudo R-squ.</strong>: The pseudo R-squared value is an alternative to the traditional <a href="https://en.wikipedia.org/wiki/Coefficient_of_determination">R-squared</a> value used in linear regression. It is a measure of the goodness of fit of the model, ranging from 0 to 1, with higher values indicating a better fit. Pseudo R-squared values are used in logistic regression because the traditional R-squared value is not well-defined for this type of model.</li><li><strong>Log-Likelihood</strong>: The log-likelihood measures how well the model explains the observed data. It is calculated by taking the logarithm of the <a href="https://en.wikipedia.org/wiki/Likelihood_function">likelihood function</a>, which represents the probability of observing the data given the model’s parameters. A higher log-likelihood value indicates a better fit.</li><li><strong>LL-Null</strong>: The log-likelihood of the null model, which is a model with no predictors (only a constant term). This value is used to calculate the likelihood ratio test, which compares the goodness of fit of our model to the goodness of fit of the null model.</li><li><strong>LLR p-value</strong>: The p-value of the likelihood ratio test, which compares the log-likelihood of the null model that has no predictors to the log-likelihood of our model. A small p-value (typically less than 0.05) indicates that our model is significantly better than the null model, meaning that at least one of the predictors has a significant effect on the target variable.</li></ul><p>Now let’s take a look at the model coefficients and statistics table that appears right below it:</p><pre>coef   std err         z      P&gt;|z|      [0.025      0.975]<br>-------------------------------------------------------------------------------<br>const             2.6317     1.633     1.612      0.107      -0.568       5.832<br>mean radius     -10.6143     5.213    -2.036      0.042     -20.832      -0.397<br>mean texture     -6.6298     3.014    -2.200      0.028     -12.537      -0.722<br>mean smoothness  -5.9281     3.517    -1.686      0.092     -12.820       0.964</pre><p>This table truncated; we actually get information about all the features in model. Let’s go over each of the columns:</p><ul><li><strong>coef</strong>: The estimated coefficients for each feature in the model. These values represent the change in the log-odds of the target variable for a one-unit increase in the corresponding feature, holding all other features constant.</li><li><strong>std err</strong>: The standard error of the estimated coefficients is a measure that describes the precision of an estimated value in a regression model and represents the uncertainty in these estimates. It indicates how much the estimated coefficient is likely to fluctuate due to the random sampling of data.<br>A smaller standard error suggests that the estimated coefficient is more precise and stable, while a larger standard error indicates more uncertainty about the true effect of a feature on the target variable.<br>Essentially, the standard error helps us understand the reliability of the estimated coefficients in a regression model and is used to calculate confidence intervals and p-values.</li><li><strong>z</strong>: The z-score of the estimated coefficients, calculated as the coefficient divided by its standard error. The z-score is used to test the null hypothesis that the true coefficient is zero (i.e., the feature has no effect on the target variable). This column isn’t particularly useful for interpretability, but the values are needed to calculate the next column.</li><li><strong>P&gt;|z|</strong>: The p-value associated with the z-score. A small p-value (typically less than 0.05) indicates that the null hypothesis can be rejected, suggesting that the corresponding feature has a significant effect on the target variable.</li><li><strong>[0.025 0.975]</strong>: The 95% confidence interval for the estimated coefficients. This interval represents the range of values within which we can be 95% confident that the true coefficient lies. If the interval does not contain zero, it suggests that the corresponding feature has a significant effect on the target variable.</li></ul><h3>Be Careful When Interpreting the Coefficients</h3><p>It’s difficult to accurately interpret the coefficients of a logistic regression. First, it’s important to understand that the coefficients in logistic regression represent the <em>log-odds</em> of the outcome variable, which is not as intuitive as the coefficients in linear regression. However, with some additional steps, we can make these coefficients more interpretable:</p><p><strong>1. Exponentiate the coefficients</strong>: By exponentiating the coefficients, we can obtain the odds ratios, which are more interpretable measures. The odds ratio represents the multiplicative change in the odds of the outcome variable for a one-unit increase in the predictor variable, holding all other variables constant.</p><p>For example, if the coefficient for a predictor variable is 0.5, the odds ratio would be exp(0.5) ≈ 1.65. This means that for every one-unit increase in the predictor variable, the odds of the outcome variable occurring increase by a factor of 1.65, assuming all other variables remain constant.</p><p><strong>2. Consider the context</strong>: When interpreting the odds ratios, it’s essential to consider the context of the predictor variables and the outcome variable. The odds ratios should be interpreted in the context of the specific problem you are trying to solve or the research question you are trying to answer.</p><p><strong>3. Assess the statistical significance</strong>: In addition to interpreting the odds ratios, it’s important to assess the statistical significance of the coefficients. This can be done by looking at the p-values or confidence intervals associated with the coefficients. If a coefficient is not statistically significant, it may not be meaningful to interpret its odds ratio.</p><p><strong>4. Be cautious with interactions and multicollinearity</strong>: When interpreting the coefficients of a logistic regression, it’s important to be cautious about potential interactions between predictor variables and multicollinearity. Interactions can make the interpretation of individual coefficients more complex, while multicollinearity can lead to unstable estimates of the coefficients.</p><p><strong>5. Consider feature scaling</strong>: If you have performed feature scaling, especially when using regularization techniques, it’s important to take this into account when interpreting the coefficients. The coefficients will be affected by the scaling, and you may need to rescale them back to their original units to make meaningful interpretations.</p><p>While interpreting the coefficients of a logistic regression can be more challenging than interpreting those of a linear regression, it is still possible and can provide valuable insights into the relationships between predictor variables and the outcome variable. By following the guidelines above, you can effectively interpret the coefficients of a logistic regression.</p><h3>Model Evaluation</h3><p>The purpose of a model is to make predictions, so while it’s important to understand the model summary, what we really care about is how well the model is performing.</p><p>To determine this, the key metrics to consider are:</p><ul><li><strong>Pseudo r-squared</strong>: This value indicates the proportion of the variance in the dependent variable that is predictable from the independent variables. A higher value (closer to 1) indicates a better fit of the model.</li><li><strong>Log-likelihood</strong>: This value measures how likely the observed data is under the fitted model. A higher value (closer to 0) indicates a better fit of the model.</li><li><strong>LLR p-value</strong>: This value tests the null hypothesis that all the coefficients of the independent variables in the model are equal to zero. A smaller p-value (typically less than 0.05) indicates that at least one of the independent variables has a significant effect on the dependent variable.</li><li><strong>Convergence</strong>: This indicates whether the model has converged, meaning that the optimization algorithm has found the best-fitting parameters for the model. If the model has not converged, it may not be a reliable representation of the data.</li></ul><p>In practice, I often look at the pseudo R-squared first, as I can easily compare it to past models I’ve built or variations of the current one. Nonetheless, it’s important to look at these other metrics as well for additional context.</p><p>While these metrics are useful, don’t forget that the true test of a model is how it does on unseen data. We still have test data to predict, so let’s do that next.</p><p>To include model evaluation by predicting on X_test, you can follow these steps:</p><ol><li>Standardize the X_test data using the same StandardScaler object that was used for X_train.</li><li>Remove highly correlated features from X_test using the same ‘to_drop’ list that was used for X_train.</li><li>Add a constant term to X_test using the sm.add_constant() function.</li><li>Make predictions using the fitted model by calling the result.predict() method on the prepared X_test data.</li><li>Calculate evaluation metrics such as accuracy, precision, recall, F1-score, and AUC using the predicted values and the true y_test values.</li></ol><p>Assuming you’ve run the previous code, here’s how to obtain our evaluation metrics:</p><pre>from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, roc_auc_score<br><br># Make predictions on the test data<br>y_pred = result.predict(X_test)<br><br># Convert predicted probabilities to binary class labels<br>y_pred_labels = np.round(y_pred)<br><br># Calculate evaluation metrics<br>accuracy  = accuracy_score(y_test, y_pred_labels)<br>precision = precision_score(y_test, y_pred_labels)<br>recall    = recall_score(y_test, y_pred_labels)<br>f1        = f1_score(y_test, y_pred_labels)<br>roc_auc   = roc_auc_score(y_test, y_pred_labels)<br><br>print(&quot;Accuracy: &quot;, accuracy)<br>print(&quot;Precision:&quot;, precision)<br>print(&quot;Recall:   &quot;, recall)<br>print(&quot;F1-score: &quot;, f1)<br>print(&quot;ROC-AUC:  &quot;, roc_auc)<br>print()<br>print(result.summary())</pre><h3>Conclusion</h3><p>In this tutorial, we’ve explored how to perform logistic regression using the StatsModels library in Python. We covered data preparation, feature selection techniques, model fitting, result interpretation, and model evaluation. By following the steps outlined in this tutorial, you can effectively apply logistic regression to your own datasets and gain valuable insights into the relationships between predictor variables and the outcome variable.</p><p>This concludes my series on logistic regression! I hope that you’ve gained a comprehensive understanding of this powerful statistical technique and its applications in various domains. By mastering logistic regression, you can enhance your data analysis skills and make more informed decisions based on the insights derived from your data.</p><p>Here’s my complete series on logistic regression:</p><ul><li><a href="https://medium.com/@vincefav/logistic-regression-an-introduction-141c1f627adf">Logistic Regression: An Introduction</a></li><li><a href="https://medium.com/@vincefav/regularization-in-logistic-regression-14b50d7cc31">Regularization in Logistic Regression</a></li><li><a href="https://medium.com/@vincefav/advanced-techniques-in-logistic-regression-part-1-ebf945686958">Advanced Techniques in Logistic Regression — Part 1</a></li><li><a href="https://medium.com/@vincefav/advanced-techniques-for-logistic-regression-and-classification-part-2-daaa968d54c">Advanced Techniques for Logistic Regression and Classification — Part 2</a></li><li><strong>Mastering Logistic Regression in Python with StatsModels</strong></li><li><a href="https://colab.research.google.com/drive/1GwdYQn9PW_XPKErp7biz6UprL9a-oln-?usp=sharing">Colab Notebook</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52bd7cc77af4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Techniques for Logistic Regression and Classification — Part 2]]></title>
            <link>https://medium.com/@vincefav/advanced-techniques-for-logistic-regression-and-classification-part-2-daaa968d54c?source=rss-b7798f9bcb53------2</link>
            <guid isPermaLink="false">https://medium.com/p/daaa968d54c</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Vincent Favilla]]></dc:creator>
            <pubDate>Fri, 02 Jun 2023 00:57:06 GMT</pubDate>
            <atom:updated>2023-06-04T20:46:37.974Z</atom:updated>
            <content:encoded><![CDATA[<h3>Advanced Techniques for Logistic Regression and Classification — Part 2</h3><p><em>View the accompanying </em><a href="https://colab.research.google.com/drive/1GwdYQn9PW_XPKErp7biz6UprL9a-oln-?usp=sharing"><em>Colab notebook</em></a><em>.</em></p><p>In <a href="https://medium.com/@vincefav/advanced-techniques-in-logistic-regression-part-1-ebf945686958">part one</a> of advanced regression techniques, we explored several advanced techniques in logistic regression, including handling nonlinear relationships, addressing multicollinearity, feature scaling and normalization, and handling categorical variables. This time around, we’ll focus on additional techniques including selection, hyperparameter tuning, model evaluation metrics, ensemble methods, and regularization path visualization.</p><p>While this tutorial is part of my logistic regression series, you’ll find that most of the topics here apply to any classification problem. Let’s dive in!</p><h3>Feature Selection Techniques</h3><p>Selecting relevant features for logistic regression is crucial for building accurate and interpretable models. There are various feature selection techniques that can be employed:</p><ul><li><strong>Filter methods</strong>: These techniques rank features based on their individual relationship with the target variable, such as <a href="https://en.wikipedia.org/wiki/Correlation">correlation</a> or <a href="https://en.wikipedia.org/wiki/Mutual_information">mutual information</a>. Examples include Pearson’s correlation coefficient and chi-squared test.</li><li><strong>Wrapper methods</strong>: These techniques evaluate feature subsets by training a model on each subset and assessing its performance. Examples include recursive feature elimination and forward selection.</li><li><strong>Embedded methods</strong>: These techniques incorporate feature selection as part of the model training process. Examples include Lasso (L1 regularization) and decision trees.</li></ul><p>We’ve <a href="https://medium.com/@vincefav/advanced-techniques-in-logistic-regression-part-1-ebf945686958">previously discussed</a> regularization methods and reducing collinearity, so let’s focus on wrapper methods. Here’s an example of using recursive feature elimination with logistic regression in scikit-learn:</p><pre>from sklearn.datasets import load_breast_cancer<br>from sklearn.model_selection import train_test_split<br>from sklearn.feature_selection import RFE<br>from sklearn.linear_model import LogisticRegression<br><br># Load the breast cancer dataset<br>data = load_breast_cancer()<br>X = data.data<br>y = data.target<br><br># Split the dataset into training and testing sets<br>X_train, X_test, y_train, y_test = train_test_split(<br>  X, y, test_size=0.2)<br><br># Create a logistic regression model<br>model = LogisticRegression(max_iter=10000)<br><br># Use RFE to select the top 5 features<br>rfe = RFE(model, n_features_to_select=5)<br>rfe.fit(X_train, y_train)<br><br># Get the selected features<br>selected_features = rfe.support_<br><br># Print the selected features<br>feature_names = data.feature_names<br>print(&quot;Selected features:&quot;)<br>for i, feature in enumerate(feature_names):<br>    if selected_features[i]:<br>        print(feature)</pre><h3>Hyperparameter Tuning with Grid Search and Randomized Search</h3><p>Hyperparameter tuning is essential for optimizing the performance of logistic regression models. Two popular techniques for hyperparameter tuning are grid search and randomized search:</p><ul><li><strong>Grid search</strong>: This technique exhaustively searches through a predefined set of hyperparameter values, evaluating each combination using cross-validation.</li><li><strong>Randomized search</strong>: This technique samples a fixed number of hyperparameter combinations from a predefined distribution, evaluating each combination using cross-validation.</li></ul><p>We saw this in <a href="https://medium.com/@vincefav/regularization-in-logistic-regression-14b50d7cc31"><strong>part two</strong></a> of the series, but now is a good time to revisit grid search now that we have more context for understanding logistic regression.</p><p>Here’s an example of using grid search in scikit-learn:</p><pre>from sklearn.datasets import load_breast_cancer<br>from sklearn.model_selection import train_test_split, GridSearchCV<br>from sklearn.linear_model import LogisticRegression<br><br># Load the breast cancer dataset<br>data = load_breast_cancer()<br>X = data.data<br>y = data.target<br><br># Split the dataset into training and testing sets<br>X_train, X_test, y_train, y_test = train_test_split(<br>  X, y, test_size=0.2)<br><br># Create a logistic regression model<br>model = LogisticRegression(max_iter=5000, solver=&#39;liblinear&#39;)<br><br># Define the parameter grid<br># (try different orders of magnitude for C)<br>param_grid = {<br>  &#39;C&#39;: [0.001, 0.01, 0.1, 1, 10, 100],<br>  &#39;penalty&#39;: [&#39;l1&#39;, &#39;l2&#39;]<br>}<br><br># Perform grid search with 5-fold cross-validation<br>grid_search = GridSearchCV(model, param_grid, cv=5, scoring=&#39;f1&#39;)<br>grid_search.fit(X_train, y_train)<br><br># Get the best hyperparameters<br>best_model = grid_search.best_estimator_<br>print(best_model)</pre><p>Grid search is extremely powerful, but it comes with at least two notable drawbacks. For one, it’s slow. It has to test every combination of hyperparameters you specify, and in the example above, we have 6 values of C and 2 penalties, leading to 12 combinations with 5 cross validations each— and I’d consider this a relatively simple grid search compared to many I’ve done before.</p><p>Secondly, there’s a small risk of overfitting your model: you may find a set of hyperparameters that perform exceptionally well on the specific cross-validation folds but do not generalize well to unseen data. On the other hand, randomized search samples a random subset of the hyperparameter space, which can help prevent overfitting by not searching the entire space exhaustively.</p><p>Let’s take a look at how to implement a randomized search in scikit-learn.</p><pre>from sklearn.datasets import load_breast_cancer<br>from sklearn.model_selection import RandomizedSearchCV, train_test_split<br>from sklearn.linear_model import LogisticRegression<br>import numpy as np<br><br># Load the breast cancer dataset<br>data = load_breast_cancer()<br>X, y = data.data, data.target<br><br># Split the data into training and testing sets<br>X_train, X_test, y_train, y_test = train_test_split(<br>  X, y, test_size=0.2)<br><br># Create a logistic regression model<br>model = LogisticRegression(max_iter=5000, solver=&#39;liblinear&#39;)<br><br># Define the parameter distribution<br>param_dist = {<br>  &#39;C&#39;: np.logspace(start=-3, stop=2, num=6), # 6 numbers from 10e-3 to 10e2<br>  &#39;penalty&#39;: [&#39;l1&#39;, &#39;l2&#39;]<br>}<br><br># Perform randomized search with 5-fold cross-validation<br>random_search = RandomizedSearchCV(model, param_dist, cv=5,<br>  scoring=&#39;f1&#39;, n_iter=6)<br>random_search.fit(X_train, y_train)<br><br># Get the best hyperparameters<br>best_model = random_search.best_estimator_<br>print(best_model)</pre><p>This will test 6 random combinations of hyperparameters, and you can make your random search more or less exhaustive by changing n_iter.</p><h3>Advanced Model Evaluation Metrics and Techniques</h3><p>We previously discussed <a href="https://medium.com/@vincefav/logistic-regression-an-introduction-141c1f627adf">common performance metrics</a> for logistic regression, including precision, recall, F1 score, confusion matrix, and ROC-AUC score. I recommend reviewing that article for a comprehensive understanding of these metrics. In this advanced discussion, I’ll introduce some additional evaluation metrics and techniques, such as the precision-recall curve, cost-sensitive metrics, model calibration, and cross-validation techniques.</p><h4>Precision-Recall Curve</h4><p>This curve plots precision against recall for different threshold values, helping you visualize the trade-off between precision and recall and choose an appropriate threshold for your specific problem.</p><pre>from sklearn.metrics import precision_recall_curve<br>import matplotlib.pyplot as plt<br>from sklearn.datasets import load_breast_cancer<br>from sklearn.model_selection import train_test_split<br>from sklearn.linear_model import LogisticRegression<br><br># Load the breast cancer dataset<br>data = load_breast_cancer()<br>X, y = data.data, data.target<br><br># Split the data into training and testing sets<br>X_train, X_test, y_train, y_test = train_test_split(<br>  X, y, test_size=0.2, random_state=42)<br><br># Train a logistic regression model<br>model = LogisticRegression(max_iter=5000)<br>model.fit(X_train, y_train)<br><br># Calculate predicted probabilities<br>y_pred_proba = model.predict_proba(X_test)[:, 1]<br><br># Calculate precision-recall curve<br>precision, recall, thresholds = precision_recall_curve(y_test, y_pred_proba)<br><br># Plot the curve<br>plt.plot(recall, precision)<br>plt.xlabel(&#39;Recall&#39;)<br>plt.ylabel(&#39;Precision&#39;)<br>plt.title(&#39;Precision-Recall Curve&#39;)<br>plt.show()</pre><p>You’ll get a graph like this for the breast cancer dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*-Y_IGz9MctAYkRa1_wraKQ.png" /></figure><p>It’s not the nicest-looking example, but you get the idea. The graph isn’t the most useful part, anyway; now that we’ve calculated the curve, we can set a target recall or precision score. Since we’re dealing with cancer in this example, it makes sense to target a recall of 1.0: we want our model to identify cancer every time it exists, even at the cost of a few false positives.</p><p>Here’s how we can do that:</p><pre>target_recall = 1.0<br><br># the `thresholds` array has one less element than<br># the `precision` and `recall` array so we slice to -1<br>idx = np.where(recall[:-1] &gt;= target_recall)[0][-1]<br>optimal_threshold = thresholds[idx]<br><br>print(&quot;Optimal decision threshold:&quot;, optimal_threshold)<br><br># Outputs...<br>&gt; Optimal decision threshold: 0.08248430372180598</pre><p>This means that if we want to do our very best to identify each case of cancer, we should have the model output a positive prediction when its predicted probability is as low as 0.08.</p><p>By the way, this is why I always have classifiers output their <em>probabilities</em> rather than their class predictions. When you have access to the probabilities, you can decide on any threshold you want for class predictions. Perhaps the clinic wants to do something like this:</p><pre>classifications = [<br>    &quot;immediate follow-up&quot;,<br>    &quot;additional tests recommended&quot;,<br>    &quot;no cancer&quot;<br>]<br><br>conditions = [<br>    y_pred_proba &gt;= optimal_threshold,<br>    (y_pred_proba &gt;= 0.01) &amp; (y_pred_proba &lt; optimal_threshold),<br>    y_pred_proba &lt; 0.01<br>]<br><br>new_labels = np.select(conditions, classifications)</pre><p>This would flag scores:</p><ul><li>Above 0.08 as requiring immediate follow-up.</li><li>Between 0.01 and 0.08 as lower priority (suggesting additional tests).</li><li>Below 0.01 as safe and not requiring follow-up.</li></ul><p>The clinic could even take it a step further and queue their follow-up patients according to their score, ensuring that those with the highest risk are seen first.</p><p>Having access to the underlying predicted probabilities allows for this kind of flexibility in decision making. Each organization or individual can tailor their use of the model to suit their specific needs and risk tolerance.</p><p>To summarize: while it can be helpful to follow typical thresholds like 0.5 for binary classification problems, there are many situations where finding and applying an optimal decision threshold is critical to make the best use of the model. This can help maximize recall or any other metric that is most relevant to the specific application, while also allowing for flexible decision-making.</p><p>Now let’s look at few other scoring metrics and techniques.</p><h4>F-beta Score</h4><p>We discussed the F1 score, which is the harmonic mean of precision and recall. The F1 score is a useful metric when dealing with imbalanced datasets, as it balances the trade-off between precision and recall. However, there might be situations where you want to give more importance to either precision or recall. This is where the F-beta score comes into play.</p><p>The F-beta score is a generalization of the F1 score, allowing you to assign different weights to precision and recall by changing the value of beta. The formula for the F-beta score is defined as:</p><pre>F-beta = (1 + beta²) * (precision * recall) / ((beta² * precision) + recall)</pre><p>If beta &gt; 1, then recall has a higher importance. If 0 &lt; beta &lt; 1, then precision has a higher importance. The F1 score is just a special case of the F-beta score when beta = 1.</p><p>Let’s see how to calculate the F-beta score using the breast cancer dataset example:</p><pre>import numpy as np<br>from sklearn.datasets import load_breast_cancer<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.model_selection import RandomizedSearchCV<br>from sklearn.metrics import fbeta_score, make_scorer<br><br># Load the breast cancer dataset<br>data = load_breast_cancer()<br>X = data.data<br>y = data.target<br><br># Define the logistic regression model<br>log_reg = LogisticRegression(max_iter=5000, solver=&#39;liblinear&#39;)<br><br># Define the hyperparameter search space<br>param_dist = {<br>    &#39;C&#39;: np.logspace(-4, 4, 20),<br>    &#39;penalty&#39;: [&#39;l1&#39;, &#39;l2&#39;]<br>}<br><br># Create the F-beta scorer with beta = 2<br>f_beta_scorer = make_scorer(fbeta_score, beta=2)<br><br># Create the RandomizedSearchCV object<br>random_search = RandomizedSearchCV(<br>  log_reg, param_distributions=param_dist,<br>  n_iter=20, scoring=f_beta_scorer, cv=5<br>)<br><br># Fit the RandomizedSearchCV object to the data<br>random_search.fit(X, y)<br><br># Print the best parameters and the corresponding F-beta score<br>print(&quot;Best parameters found: &quot;, random_search.best_params_)<br>print(&quot;Best F-beta score: &quot;, random_search.best_score_)</pre><p>In this example, we’ve set beta to 2, which means that recall has a higher importance than precision. You can change the value of beta to suit your needs.</p><p>By using the F-beta score, you can fine-tune your model’s performance according to the specific requirements of your application. We’ve been an example where recall is more important than precision, but there are many instances where you should prioritize precision instead. For example, in a spam detection system, you might want to prioritize precision (0 &lt; beta &lt; 1) to avoid marking legitimate emails as spam.</p><p>The F-beta score is a powerful evaluation metric that allows you to balance the trade-off between precision and recall according to your specific needs. By combining this metric with the precision-recall curve and optimal decision thresholds, you can build more effective and flexible classification models that cater to a wide range of applications and risk tolerances.</p><h4>Model Calibration</h4><p><strong>Calibration </strong>measures how well the predicted probabilities of a model match the true probabilities of the outcomes. A well-calibrated model should have predicted probabilities close to the true probabilities.</p><p>Let’s use weather forecasts as an example. If a weather service says there’s an 80% chance of rain, you should ideally be able to look at their past forecasts and find that it rained 80% of the time when the forecast was for an 80% chance of rain.</p><p>However, if their weather model is poorly calibrated, the actual probability of it raining might be much lower or higher than 80%. For weather this is usually just a mild inconvenience, but for cancer detection it can lead to incorrect decisions and harmful consequences.</p><p>There are several ways to measure calibration, but one common method is to use a <strong>calibration plot</strong>. A calibration plot shows the predicted probabilities on the x-axis and the observed frequencies on the y-axis. Ideally, the plot should show a diagonal line, indicating that the predicted probabilities match the true probabilities.</p><p>Here’s an example of a calibration plot for a logistic regression model:</p><pre>from sklearn.calibration import calibration_curve, CalibratedClassifierCV<br>import matplotlib.pyplot as plt<br>from sklearn.datasets import load_breast_cancer<br>from sklearn.model_selection import train_test_split<br>from sklearn.linear_model import LogisticRegression<br><br># Load the breast cancer dataset<br>data = load_breast_cancer()<br>X, y = data.data, data.target<br><br># Split the data into training and testing sets<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)<br><br># Train a logistic regression model<br>model = LogisticRegression(max_iter=5000)<br>model.fit(X_train, y_train)<br><br># Calculate predicted probabilities using the calibrated model<br>y_pred_proba = model.predict_proba(X_test)[:, 1]<br><br># Calculate calibration curve<br>fraction_of_positives, mean_predicted_value = calibration_curve(<br>  y_test, y_pred_proba, n_bins=10)<br><br># Plot the calibration curve<br>plt.plot(fraction_of_positives, mean_predicted_value, &#39;x&#39;)<br>plt.plot([0, 1], [0, 1], &#39;--&#39;, color=&#39;gray&#39;)<br>plt.xlabel(&#39;Fraction of positives&#39;)<br>plt.ylabel(&#39;Mean predicted value&#39;)<br>plt.title(&#39;Calibration Curve&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*Oo_m0HXR8no-t_f67YIzEA.png" /></figure><p>As you can see, the blue x’s fall close to the gray dotted line, indicating that the model is well-calibrated. An overconfident model would have dots that fall mostly above the line, while the dots on an underconfident model would fall below.</p><h3>Ensemble Methods for Logistic Regression</h3><p>Ensemble methods combine multiple models to improve overall performance. Two popular ensemble techniques for logistic regression are:</p><ul><li><strong>Bagging</strong>: This technique trains multiple base models independently on random subsets of the training data, then combines their predictions through majority voting or averaging. An example is the BaggingClassifier in scikit-learn.</li><li><strong>Boosting</strong>: This technique trains multiple base models sequentially, with each model learning from the errors of its predecessor. An example is the AdaBoostClassifier in scikit-learn.</li></ul><p>Here’s an example of using bagging with logistic regression in scikit-learn:</p><pre>from sklearn.datasets import load_breast_cancer<br>from sklearn.ensemble import BaggingClassifier<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import roc_auc_score<br><br># Load the breast cancer dataset<br>data = load_breast_cancer()<br>X = data.data<br>y = data.target<br><br># Split the data into training and testing sets<br>X_train, X_test, y_train, y_test = train_test_split(<br>  X, y, test_size=0.2)<br><br># Create a logistic regression model<br>base_model = LogisticRegression(max_iter=5000, solver=&#39;liblinear&#39;)<br><br># Create a bagging ensemble of logistic regression models<br>bagging_model = BaggingClassifier(<br>  estimator=base_model, n_estimators=10)<br>bagging_model.fit(X_train, y_train)<br><br># Evaluate the ensemble model<br>y_pred = bagging_model.predict(X_test)<br>score = roc_auc_score(y_test, y_pred)<br>print(&quot;Bagging ROC-AUC score:&quot;, score)</pre><p>And an example of boosting using AdaBoost:</p><pre>from sklearn.datasets import load_breast_cancer<br>from sklearn.ensemble import AdaBoostClassifier<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import roc_auc_score<br><br># Load the breast cancer dataset<br>data = load_breast_cancer()<br>X = data.data<br>y = data.target<br><br># Split the data into training and testing sets<br>X_train, X_test, y_train, y_test = train_test_split(<br>  X, y, test_size=0.2)<br><br># Create a logistic regression model<br>base_model = LogisticRegression(solver=&#39;liblinear&#39;)<br><br># Create an AdaBoost ensemble of logistic regression models<br>boosting_model = AdaBoostClassifier(<br>  estimator=base_model, n_estimators=50)<br>boosting_model.fit(X_train, y_train)<br><br># Evaluate the ensemble model<br>y_pred = boosting_model.predict(X_test)<br>score = roc_auc_score(y_test, y_pred)<br>print(&quot;Bagging ROC-AUC score:&quot;, score)</pre><h3>Regularization Path Visualization</h3><p>Visualizing the regularization path can help you understand the effect of regularization on the coefficients of logistic regression models and the trade-off between model complexity and generalization. As the regularization strength C increases, the penalty term in the loss function becomes less dominant, allowing the coefficients to take on a wider range of values.</p><p>Here’s an example of visualizing the regularization path using scikit-learn and matplotlib:</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.datasets import load_breast_cancer<br>from sklearn.model_selection import train_test_split<br><br># Load the breast cancer dataset<br>data = load_breast_cancer()<br>X, y = data.data, data.target<br><br># Split the data into training and testing sets<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)<br><br># Train a logistic regression model<br>model = LogisticRegression(max_iter=5000)<br>model.fit(X_train, y_train)<br><br># Define a range of regularization strengths<br>C_values = np.logspace(-2, 4, 20)<br><br># Train logistic regression models with different regularization strengths<br>coefficients = []<br>for C in C_values:<br>    model = LogisticRegression(penalty=&#39;l1&#39;, solver=&#39;liblinear&#39;, C=C)<br>    model.fit(X_train, y_train)<br>    coefficients.append(model.coef_)<br><br># Reshape the coefficients array to match the dimensions of the C_values array<br>coefficients = np.array(coefficients).reshape(len(C_values), -1)<br><br># Plot the regularization path<br>plt.figure(figsize=(10, 6))<br>plt.plot(np.log10(C_values), coefficients)<br>plt.xlabel(&#39;log10(C)&#39;)<br>plt.ylabel(&#39;Coefficients&#39;)<br>plt.title(&#39;Regularization Path&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*xF6FxhOKOO0-I2QGgn_UKg.png" /></figure><p>You can see how the coefficients change as the regularization strength increases. The lines start close to zero at 10e-4 and branch out all over the place as they reach 10e4. This branching effect occurs because the penalty term in the loss function becomes less dominant as the regularization strength increases, allowing the coefficients to take on a wider range of values.</p><p>While grid search and cross-validation are the go-to methods for selecting the optimal regularization strength, regularization path visualization can serve as a complementary tool for exploring and interpreting your logistic regression model. It provides valuable insights into the relationship between regularization strength and model coefficients, feature importance, and the trade-off between model complexity and generalization. By combining regularization path visualization with techniques like cross-validation, you can gain a deeper understanding of your model and make more informed decisions when selecting the appropriate regularization strength.</p><h3>Conclusion</h3><p>In this tutorial, we explored more advanced techniques for classification and logistic regression, including feature selection, hyperparameter tuning, model evaluation metrics, ensemble methods, and regularization path visualization. By applying these techniques, you can build more accurate and interpretable logistic regression models for various real-world applications.</p><p>My complete series on logistic regression:</p><ul><li><a href="https://medium.com/@vincefav/logistic-regression-an-introduction-141c1f627adf">Logistic Regression: An Introduction</a></li><li><a href="https://medium.com/@vincefav/regularization-in-logistic-regression-14b50d7cc31">Regularization in Logistic Regression</a></li><li><a href="https://medium.com/@vincefav/advanced-techniques-in-logistic-regression-part-1-ebf945686958">Advanced Techniques in Logistic Regression — Part 1</a></li><li><strong>Advanced Techniques for Logistic Regression &amp; Classification — Part 2</strong></li><li><a href="https://medium.com/@vincefav/mastering-logistic-regression-in-python-with-statsmodels-52bd7cc77af4">Mastering Logistic Regression in Python with StatsModels</a></li><li><a href="https://colab.research.google.com/drive/1GwdYQn9PW_XPKErp7biz6UprL9a-oln-?usp=sharing">Colab Notebook</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=daaa968d54c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Techniques in Logistic Regression — Part 1]]></title>
            <link>https://medium.com/@vincefav/advanced-techniques-in-logistic-regression-part-1-ebf945686958?source=rss-b7798f9bcb53------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebf945686958</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Vincent Favilla]]></dc:creator>
            <pubDate>Thu, 01 Jun 2023 02:09:19 GMT</pubDate>
            <atom:updated>2023-06-06T15:56:56.514Z</atom:updated>
            <content:encoded><![CDATA[<h3>Advanced Techniques in Logistic Regression — Part 1</h3><p><em>View the accompanying </em><a href="https://colab.research.google.com/drive/1GwdYQn9PW_XPKErp7biz6UprL9a-oln-?usp=sharing"><em>Colab notebook</em></a><em>.</em></p><p>So far in this logistic regression series, we’ve explored the <a href="https://medium.com/@vincefav/logistic-regression-an-introduction-141c1f627adf">basics of logistic regression</a> and regularization, <a href="https://medium.com/@vincefav/regularization-in-logistic-regression-14b50d7cc31">discussed L1 and L2 regularization</a>, and explored the concept of convexity in the context of regularization. Now it’s time to delve into advanced techniques in logistic regression, including handling nonlinear relationships, addressing multicollinearity, feature scaling and normalization, and handling categorical variables. Buckle up — there’s lots to cover!</p><h3>Handling Nonlinear Relationships</h3><p>Logistic regression assumes a linear relationship between the features and the log-odds of the target variable. However, in real-world problems, the relationship between features and the target variable can often be nonlinear. To capture nonlinear relationships, we can use the following techniques:</p><h4>Polynomial features</h4><p>Creating new features by raising existing features to higher degrees can help capture nonlinear relationships. For example, if we have a feature x, we can create new features x², x³, etc. Scikit-learn provides the PolynomialFeatures class to generate polynomial features easily. Here’s the simplest example:</p><pre>import pandas as pd<br>from sklearn.preprocessing import PolynomialFeatures<br><br>df = pd.DataFrame()<br>df[&#39;x&#39;] = pd.Series([1,2,3])<br><br>poly = PolynomialFeatures(degree=2)<br><br># Make sure to use double brackets around the column name<br>X_poly = poly.fit_transform(df[[&#39;x&#39;]])<br><br># Give your new polynomnial features descriptive column names<br>X_poly = pd.DataFrame(X_poly, columns=[&#39;x**0&#39;, &#39;x**1&#39;, &#39;x**2&#39;])<br><br># Concat to your original dataframe<br>df_concat = pd.concat([df, X_poly], axis=1)<br><br>pd.DataFrame(X_poly)</pre><p>Your dataframe will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*E9Rc-bd1xi-7iQGlshjR3Q.png" /></figure><p>Column 0 represents X⁰ (i.e., 1), while column 1 contains the original values (X¹). Finally, column 2 is X².</p><p>Now you’re ready to see if raising this feature to a higher degree will improve your model’s performance.</p><h4>Interaction terms</h4><p>Now, if you already have some experience with pandas, you might be thinking that you could just as easily create new columns by doing something along the lines of df[&#39;x squared&#39;] = df[&#39;x&#39;]**2 .</p><p>You’d be right. The real power of PolynomialFeatures comes from its ability to create interaction terms.</p><p>Creating new features by multiplying two or more existing features can help capture the combined effect of multiple features on the target variable. For example, if we have features x and y, PolynomialFeatures will by default create a new feature x*y .</p><pre>import pandas as pd<br>from sklearn.preprocessing import PolynomialFeatures<br><br>df = pd.DataFrame()<br>df[&#39;x&#39;] = pd.Series([1,2,3])<br>df[&#39;y&#39;] = pd.Series([4,7,11])<br><br>poly = PolynomialFeatures(degree=2)<br><br>X_poly = poly.fit_transform(df[[&#39;x&#39;,&#39;y&#39;]])<br><br>X_poly = pd.DataFrame(<br>  X_poly,<br>  columns=[&#39;bias&#39;, &#39;x&#39;, &#39;y&#39;, &#39;x**2&#39;, &#39;x*y&#39;, &#39;y**2&#39;]<br>)</pre><p>X_poly will now look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*8TdnbsIOMSZQEh5zd9co6g.png" /></figure><p>And it becomes even more handy as you add more columns.</p><p>Some other nonlinear relationships you may run into include exponential and logarithmic relationships. But because PolynomialFeatures is, well, polynomial, it’s not equipped to deal with non-integer exponents. Instead we can use scikit-learn’s FunctionTransformer .</p><pre>import pandas as pd<br>import numpy as np<br>from sklearn.preprocessing import FunctionTransformer<br><br># Create some sample data<br>df = pd.DataFrame()<br>df[&#39;x&#39;] = pd.Series([1,2,3])<br>df[&#39;y&#39;] = pd.Series([4,7,11])<br><br># Define a function to apply the logarithm transformation<br>def log_transform(X):<br>    # it&#39;s helpful to add a small constant since log(0) is undefined<br>    return np.log(X + .01) <br><br># Create a FunctionTransformer with the log_transform function<br>log_transformer = FunctionTransformer(log_transform)<br><br># Fit and transform the data<br>X_log = log_transformer.fit_transform(df)<br><br>df_concat = pd.concat([df, X_log], axis=1)</pre><p>Alternatively, this may in fact be a case where it’s easier to use a vector operation:</p><pre>import pandas as pd<br>import numpy as np<br><br>df = pd.DataFrame()<br>df[&#39;x&#39;] = pd.Series([1,2,3])<br>df[&#39;y&#39;] = pd.Series([4,7,11])<br><br>cols = df.columns<br><br>for col in cols:<br>  df[f&#39;log_{col}&#39;] = np.log(df[col] + 0.01)</pre><p>You could do something similar for creating columns for square roots, if you’re so inclined.</p><p>Now that we’ve done some feature transformations, let’s look at other ways to improve a model’s performance.</p><h3>Addressing Multicollinearity</h3><p><strong>Multicollinearity </strong>occurs when two or more features in a dataset are highly correlated, which can lead to unstable estimates of the model coefficients and reduced interpretability. To detect and handle multicollinearity, we can use the following techniques:</p><h4>Correlation matrix</h4><p>Calculate the correlation coefficients between all pairs of features and visualize them using a heatmap. Features with high correlation coefficients can be considered for removal or combined into a single feature.</p><pre>import pandas as pd<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br><br>df = pd.DataFrame({<br>    &#39;a&#39;: [1,2,3,4],<br>    &#39;b&#39;: [4,2,4,3],<br>    &#39;c&#39;: [5,5,1,0],<br>    &#39;d&#39;: [2,2,3,0],<br>})<br><br>corr_matrix = df.corr()<br>sns.heatmap(corr_matrix, annot=True)<br>plt.show()</pre><p>This gives us the following heatmap:</p><figure><img alt="heatmap" src="https://cdn-images-1.medium.com/max/565/1*LLHf48zy1HbzsP5pHqE6xA.png" /></figure><p>We can see that there’s a very strong negative relationship between variables “a” and “c”, and your model may improve if you remove one of them. If you want a good rule of thumb, any variables with a ±0.7 correlation or stronger should be considered for removal.</p><h4>Variance Inflation Factor (VIF)</h4><p>VIF measures the extent to which the variance of a model coefficient is inflated due to multicollinearity. Features with a VIF greater than a certain threshold (e.g., 5 or 10) can be considered for removal or combined into a single feature.</p><pre>from statsmodels.stats.outliers_influence import variance_inflation_factor<br><br>vif = [variance_inflation_factor(df.values, i) for i in range(df.shape[1])]<br><br># Display VIF<br>pd.DataFrame({&#39;vif&#39;: vif[0:]}, index=df.columns).T</pre><p>Interestingly, this method singles out “b” as having a high VIF and thus a candidate for removal. Bear in mind that although “a” and “c” have a strong correlation with each other, they may not have a strong correlation with the other variables in the dataset. On the other hand, “b” may have a high correlation with multiple other variables, leading to a high VIF.</p><p>As always, experimentation and cross-validation is key to building a robust model.</p><h4>Regularization</h4><p>As discussed in my last article, <a href="https://medium.com/@vincefav/regularization-in-logistic-regression-14b50d7cc31">regularization techniques</a> like L1 and L2 can help mitigate the effects of multicollinearity by shrinking the coefficients of correlated features.</p><h4>Feature Scaling and Normalization</h4><p>Feature scaling is important in logistic regression, as it ensures that all features contribute equally to the model. Different scaling techniques include:</p><p>- MinMaxScaler: Scales features to a specific range, usually such that 0 represents the minimum value and 1 represents the maximum value.</p><pre>from sklearn.preprocessing import MinMaxScaler<br><br>scaler = MinMaxScaler()<br>X_scaled = scaler.fit_transform(X)</pre><p>- StandardScaler: Standardizes features by converting numbers to their z-scores. A z-score is the number of standard deviations (positive or negative) a number is away from the mean.</p><pre>from sklearn.preprocessing import StandardScaler<br><br>scaler = StandardScaler()<br>X_scaled = scaler.fit_transform(X)</pre><p>Which scaling technique to use depends on the data and the model. For example, if the data is normally distributed, then StandardScaler is a good choice. If the data is not normally distributed, then MinMaxScaler may be a better choice.</p><h3>Handling Categorical Variables</h3><p>Logistic regression requires numerical input features. To include categorical variables in the model, we need to convert them into numerical values using encoding techniques:</p><p><strong>One-hot encoding</strong>: Creates binary features for each category of a categorical variable. This can be done in a number of ways, but I think the pandas get_dummies() function is the easiest:</p><pre>import pandas as pd<br><br># drop_first helps to reduce collinearity<br>df_dummified = pd.get_dummies(df, prefix=&#39;category&#39;, drop_first=True)</pre><p>Be careful doing this if you have a lot of different categorical values, as it can easily create hundreds or even thousands of new columns. If you want finer control over what gets one-hot encoded, you can can always pass a column to get_dummies() instead and then concatenate it to your dataframe:</p><pre>import pandas as pd<br><br># Let&#39;s say we have a &quot;month&quot; column we need to one-hot encode<br>month_dummified = pd.get_dummies(df[&#39;month&#39;], prefix=&#39;category&#39;,<br>  drop_first=True)<br><br>df = pd.concat([df, month_dummified], axis=1)</pre><p><strong>Ordinal encoding</strong>: Assigns an integer value to each category of a categorical variable based on its rank. This can be done using scikit-learn’s OrdinalEncoder class.</p><pre>import pandas as pd<br>from sklearn.preprocessing import OrdinalEncoder<br><br>encoder = OrdinalEncoder()<br>X_encoded = encoder.fit_transform(df[[&#39;month&#39;]])<br># Note the double brackets to keep it as a DataFrame<br><br># Convert the encoded data to a dataframe and assign column names<br>X_encoded_df = pd.DataFrame(X_encoded, columns=[&#39;encoded_month&#39;])<br># Replace &#39;encoded_month&#39; with an appropriate column name<br><br># Concatenate the encoded dataframe with the original dataframe<br>df = pd.concat([df, X_encoded_df], axis=1)</pre><h3>Conclusion</h3><p>We covered a lot here. In this post we delved into advanced techniques in logistic regression, including handling nonlinear relationships, addressing multicollinearity, feature scaling and normalization, and handling categorical variables. These techniques will help you to build more accurate and robust logistic regression models.</p><p>In the next part of the series, we’ll continue exploring advanced techniques, such as feature selection, hyperparameter tuning, ensemble methods, and regularization path visualization. For further reading and resources, consider exploring the following links:</p><ul><li><a href="https://scikit-learn.org/stable/index.html">Scikit-learn documentation</a></li><li><a href="https://www.statsmodels.org/stable/index.html">Statsmodels documentation</a></li><li><a href="https://contrib.scikit-learn.org/category_encoders/index.html">Category Encoders library</a></li></ul><p>My complete series on logistic regression:</p><ul><li><a href="https://medium.com/@vincefav/logistic-regression-an-introduction-141c1f627adf">Logistic Regression: An Introduction</a></li><li><a href="https://medium.com/@vincefav/regularization-in-logistic-regression-14b50d7cc31">Regularization in Logistic Regression</a></li><li><strong>Advanced Techniques in Logistic Regression — Part 1</strong></li><li><a href="https://medium.com/@vincefav/advanced-techniques-for-logistic-regression-and-classification-part-2-daaa968d54c">Advanced Techniques for Logistic Regression and Classification — Part 2</a></li><li><a href="https://medium.com/@vincefav/mastering-logistic-regression-in-python-with-statsmodels-52bd7cc77af4">Mastering Logistic Regression in Python with StatsModels</a></li><li><a href="https://colab.research.google.com/drive/1GwdYQn9PW_XPKErp7biz6UprL9a-oln-?usp=sharing">Colab Notebook</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebf945686958" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Regularization in Logistic Regression]]></title>
            <link>https://medium.com/@vincefav/regularization-in-logistic-regression-14b50d7cc31?source=rss-b7798f9bcb53------2</link>
            <guid isPermaLink="false">https://medium.com/p/14b50d7cc31</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[Vincent Favilla]]></dc:creator>
            <pubDate>Tue, 30 May 2023 01:40:00 GMT</pubDate>
            <atom:updated>2023-06-06T15:55:50.389Z</atom:updated>
            <content:encoded><![CDATA[<p><em>View the accompanying </em><a href="https://colab.research.google.com/drive/1GwdYQn9PW_XPKErp7biz6UprL9a-oln-?usp=sharing"><em>Colab notebook</em></a><em>.</em></p><p>In my <a href="https://medium.com/@vincefav/logistic-regression-an-introduction-141c1f627adf">previous article</a>, we explored the basics of logistic regression. Now, we’ll focus on regularization, a technique used to prevent overfitting and improve model generalization in logistic regression.</p><p>In this second part of the series, we’ll discuss L1 and L2 regularization, explain the concept of convexity in the context of regularization, and provide guidance on choosing the appropriate regularization technique. We’ll also provide examples, illustrations, and visual aids to help you better understand these concepts.</p><h3>Regularization: A Brief Overview</h3><p>Regularization is a technique that adds a penalty term to the <strong>cost function</strong>, which measures how well the model is performing. This penalty term helps control the size of the coefficients (also called weights) in the model. Smaller coefficients usually result in a simpler model that is less likely to overfit. Regularization helps to balance the trade-off between model complexity and model fit, preventing the model from relying too heavily on any single predictor variable.</p><p>There are different types of regularization terms, such as L1 and L2. These terms are calculated using <strong>p-norms</strong>, which have different effects on the model coefficients.</p><h3>P-Norms and Regularization</h3><p>P-norms are a family of mathematical functions used to calculate the “size” or “magnitude” of a <a href="https://en.wikipedia.org/wiki/Row_and_column_vectors">vector</a>. In the context of regularization, p-norms are used to calculate the penalty term based on the coefficients of the model. The most common p-norms used in regularization are the L1-norm (p=1) and the L2-norm (p=2).</p><p>The L1-norm is calculated as the sum of the absolute values of the coefficients, while the L2-norm is calculated as the square root of the sum of the squares of the coefficients. Different p-norms have different effects on the model coefficients, leading to different regularization techniques.</p><h3>L1, L2, and Elastic Net Regularization</h3><p>In regularization techniques, the penalty term is controlled by a parameter called <strong>lambda </strong>(λ). Lambda determines the strength of the regularization effect, with larger values resulting in stronger regularization and smaller values resulting in weaker regularization. By adjusting lambda, we can control the balance between model complexity and model fit. In this section, we will discuss L1, L2, and Elastic Net regularization techniques and their relationship with lambda.</p><h3>L1 Regularization (Lasso)</h3><p>L1 regularization, also known as Lasso, uses the L1-norm as the penalty term. The L1-norm is calculated as the sum of the absolute values of the coefficients. Mathematically, the L1 penalty term is defined as:</p><pre>L1_penalty = lambda * sum(abs(coefficients))</pre><p>L1 regularization tends to create sparser models, meaning some coefficients will be exactly zero, effectively removing certain features from the model. This can be useful for feature selection, especially when there are many irrelevant features or when interpretability is important.</p><h3>L2 Regularization (Ridge)</h3><p>L2 regularization, also known as Ridge, uses the L2-norm as the penalty term. The L2-norm is calculated as the square root of the sum of the squares of the coefficients. Mathematically, the L2 penalty term is defined as:</p><pre>L2_penalty = lambda * sum(coefficients ** 2)</pre><p>L2 regularization tends to create models with smaller coefficients but does not force them to be exactly zero. This results in a more balanced model that still considers all features but with reduced importance.</p><h3>Elastic Net Regularization</h3><p>Elastic Net regularization is a combination of L1 and L2 regularization. It uses both the L1-norm and the L2-norm as penalty terms, with a mixing parameter (alpha) to control the balance between the two. Mathematically, the Elastic Net penalty term is defined as:</p><pre>ElasticNet_penalty = alpha * L1_penalty + (1 - alpha) * L2_penalty</pre><p>Elastic Net regularization can provide a balance between the sparsity of L1 regularization and the smoothness of L2 regularization, making it a useful option when it’s unclear which regularization technique to use. By adjusting the values of lambda and alpha, we can fine-tune the regularization effect to achieve the desired balance between model complexity and fit.</p><h3>Intuition Behind L1 and L2 Effects on Coefficients</h3><p>L1 regularization penalizes the model for having disproportionately large coefficients, after appropriately scaling the predictor variables. This encourages the model to rely on a smaller set of predictor variables, leading to sparser models with some coefficients being exactly zero.</p><p>L2 regularization, on the other hand, adds a “cost” to the model for having large squared coefficients. This encourages the model to distribute the importance of predictor variables more evenly across all features, resulting in smaller coefficients but not necessarily zero.</p><h3>Convexity and Regularization</h3><p>As we know, the goal of logistic regression is to minimize the cost function. This means we want to find the best combination of the model’s coefficients that results in the lowest cost. Doing this helps train the model to make accurate predictions on new, unseen data.</p><p><strong>Convexity </strong>is a mathematical property that describes the shape of the cost function in logistic regression. A cost function is said to be convex if it has a single global minimum, meaning that there is only one set of coefficients that minimizes the cost function. Convexity is an important property because it guarantees that the optimization algorithm used to minimize the cost function will converge to the global minimum, regardless of the coefficients the algorithm starts with.</p><p>L2 regularization induces convexity in the cost function by adding a quadratic penalty term, which makes the cost function smoother and easier to optimize. L1 regularization, on the other hand, does not induce convexity but can still lead to sparse solutions.</p><h3>Challenges with Non-Convex Cost Functions</h3><p>Optimizing non-convex cost functions, such as those resulting from L1 regularization, can be more challenging due to the presence of multiple local minima, which means that the optimization algorithm may converge to a suboptimal solution — which is a fancy way of saying that your trained model may not be as accurate as it could be.</p><p>In practice, however, L1 regularization often leads to sparse solutions that are still useful for feature selection and model interpretation.</p><h3>Choosing the Appropriate Regularization Technique</h3><p>The choice of regularization technique depends on the specific problem and the desired properties of the model, such as sparsity or simplicity. Here are some guidelines to help you choose the appropriate regularization technique:</p><ul><li>If you have many irrelevant features or need a more interpretable model, consider using L1 regularization, as it creates sparser models with some coefficients being exactly zero.</li><li>If you want a more balanced model that considers all features but with reduced importance, consider using L2 regularization, as it creates models with smaller coefficients but not necessarily zero.</li><li>If you’re unsure which technique to use, consider trying Elastic Net regularization, which combines L1 and L2 regularization and allows you to control the balance between the two.</li><li>Compare the performance of different regularization techniques using cross-validation to choose the best one for your specific problem.</li></ul><h3>The Role of the Regularization Strength Parameter (Lambda)</h3><p>The regularization strength parameter (lambda) controls the balance between model complexity and fit. A larger lambda value results in a stronger regularization effect, leading to smaller coefficients and a simpler model. Conversely, a smaller lambda value results in a weaker regularization effect, allowing the model to fit the data more closely. Tuning the lambda parameter is crucial for finding the optimal balance between model complexity and fit.</p><h3>Implementing Regularization in Scikit-learn</h3><p>Scikit-learn is a popular machine learning library in Python that provides built-in support for logistic regression with regularization. The LogisticRegression class allows you to specify the type of regularization (L1, L2, or Elastic Net) and the regularization strength (C, which is the inverse of lambda) when creating a new model. Here’s an example of how to create a logistic regression model with L1 regularization and a specific regularization strength:</p><pre>from sklearn.linear_model import LogisticRegression<br><br># Create a logistic regression model with L1 regularization<br># and a specific regularization strength.<br>model = LogisticRegression(penalty=&#39;l1&#39;, C=1.0, solver=&#39;liblinear&#39;)</pre><p>Cross-validation is a model evaluation technique used to assess the performance of a machine learning model on unseen data. It involves dividing the dataset into multiple subsets, or “folds,” and iteratively training the model on different combinations of these folds while testing its performance on the remaining fold.</p><p>This process is repeated for each fold, and the model’s performance is averaged across all iterations. Cross-validation helps to estimate the model’s generalization ability and can be used to compare the performance of different regularization techniques. By selecting the regularization technique that yields the best cross-validation performance, you can ensure that your model is less likely to overfit and will perform well on new, unseen data.</p><p>The Python code for cross-validation typically looks something like this:</p><pre>from sklearn.linear_model import LogisticRegression<br>from sklearn.model_selection import cross_val_score<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.datasets import load_iris<br><br># Load the Iris dataset<br>data = load_iris()<br>X, y = data.data, data.target<br><br># When using regularization, you should scale the features first.<br># Here&#39;s how:<br>scaler = StandardScaler()<br>X = scaler.fit_transform(X)<br><br># Create a logistic regression model with L1 regularization<br># and a specific regularization strength.<br>model = LogisticRegression(penalty=&#39;l1&#39;, C=1.0, solver=&#39;liblinear&#39;)<br><br># Perform 5-fold cross-validation<br>cv_scores = cross_val_score(model, X, y, cv=5, scoring=&#39;accuracy&#39;)<br><br># Calculate the average cross-validation score<br>mean_cv_score = cv_scores.mean()<br><br>print(&quot;Average 5-fold cross-validation score:&quot;, mean_cv_score)</pre><p>You can test different settings using this code, but it’s more efficient to run a <strong>grid search</strong>, which tries different combinations of hyperparameters to determine the best model:</p><pre>from sklearn.linear_model import LogisticRegression<br>from sklearn.model_selection import GridSearchCV<br>from sklearn.datasets import load_iris<br>from sklearn.preprocessing import StandardScaler<br>import warnings<br>warnings.filterwarnings(&#39;ignore&#39;)<br><br># Load the Iris dataset<br>data = load_iris()<br>X, y = data.data, data.target<br><br># Scale the features<br>scaler = StandardScaler()<br>X_scaled = scaler.fit_transform(X)<br><br># Create a logistic regression model<br>model = LogisticRegression(solver=&#39;saga&#39;, max_iter=5000)<br><br># Create a list of regularization strengths and penalties to test<br>params = {<br>    &#39;C&#39;: [0.001, 0.01, 0.1, 1.0, 10.0, 100.0],<br>    &#39;penalty&#39;: [None, &#39;l1&#39;, &#39;l2&#39;, &#39;elasticnet&#39;],<br>    &#39;l1_ratio&#39;: [.25, .50, .75] # this is &#39;alpha&#39; as described earlier<br>}<br><br># Perform 5-fold cross-validation with different regularization strengths and penalties<br>clf = GridSearchCV(model, params, cv=5, scoring=&#39;accuracy&#39;)<br>clf.fit(X_scaled, y)<br><br># Print the best regularization strength and penalty<br>print(&quot;Best regularization strength:&quot;, clf.best_params_[&#39;C&#39;])<br>print(&quot;Best penalty:&quot;, clf.best_params_[&#39;penalty&#39;])<br><br>if clf.best_params_[&#39;penalty&#39;] == &#39;elasticnet&#39;:<br>    print(&quot;Best alpha:&quot;, clf.best_params_[&#39;l1_ratio&#39;])</pre><h3>Conclusion</h3><p>In this second part of my logistic regression series, we delved into regularization — discussing L1 and L2 regularization, and explored the concept of convexity in the context of regularization.</p><p>Regularization has numerous real-world applications, and you’ll find it in just about every domain where machine learning and deep learning models are used. This includes computer vision, natural language processing, speech recognition, and many more areas. By using regularization techniques, we can create more robust and generalizable models that perform well on new, unseen data.</p><p>In the next part of this series, we’ll explore the practical aspects of implementing a logistic regression, including handling nonlinear relationships, addressing multicollinearity, and diving deeper into the use of grid search to create optimal models.</p><p>My complete series on logistic regression:</p><ul><li><a href="https://medium.com/@vincefav/logistic-regression-an-introduction-141c1f627adf">Logistic Regression: An Introduction</a></li><li><strong>Regularization in Logistic Regression</strong></li><li><a href="https://medium.com/@vincefav/advanced-techniques-in-logistic-regression-part-1-ebf945686958">Advanced Techniques in Logistic Regression — Part 1</a></li><li><a href="https://medium.com/@vincefav/advanced-techniques-for-logistic-regression-and-classification-part-2-daaa968d54c">Advanced Techniques for Logistic Regression and Classification — Part 2</a></li><li><a href="https://medium.com/@vincefav/mastering-logistic-regression-in-python-with-statsmodels-52bd7cc77af4">Mastering Logistic Regression in Python with StatsModels</a></li><li><a href="https://colab.research.google.com/drive/1GwdYQn9PW_XPKErp7biz6UprL9a-oln-?usp=sharing">Colab Notebook</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14b50d7cc31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logistic Regression: An Introduction]]></title>
            <link>https://medium.com/@vincefav/logistic-regression-an-introduction-141c1f627adf?source=rss-b7798f9bcb53------2</link>
            <guid isPermaLink="false">https://medium.com/p/141c1f627adf</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Vincent Favilla]]></dc:creator>
            <pubDate>Mon, 29 May 2023 23:31:44 GMT</pubDate>
            <atom:updated>2023-06-04T20:45:25.805Z</atom:updated>
            <content:encoded><![CDATA[<p><em>View the accompanying </em><a href="https://colab.research.google.com/drive/1GwdYQn9PW_XPKErp7biz6UprL9a-oln-?usp=sharing"><em>Colab notebook</em></a><em>.</em></p><p>Logistic regression is a popular machine learning technique used to predict the probability of an event occurring based on input data. For example, it can be used to predict whether a customer will make a purchase based on their browsing history and demographic information. In this introductory post of my logistic regression series, we’ll explore the basics of logistic regression, discuss its assumptions, and see some examples with actual data.</p><h3>Logistic Regression vs. Linear Regression</h3><p>While linear regression is used to model the relationship between predictor variables and a continuous outcome variable, logistic regression is used for binary classification problems, where the outcome variable has only two possible values. Logistic regression models the probability of the outcome occurring given the predictor variables, and classifies the outcome based on a threshold probability value.</p><h3>Logistic Regression: A Brief Overview</h3><p>Logistic regression is a type of regression analysis used for predicting binary outcomes. It models the relationship between a set of predictor variables and a binary outcome variable by estimating the probability of the outcome occurring given the predictor variables.</p><h3>Logit Function</h3><p>The logit function is the natural logarithm of the odds of the outcome occurring, which is the ratio of the probability of the outcome occurring to the probability of the outcome not occurring. Mathematically, the logit function is defined as:</p><pre>logit(p) = log(p / (1 - p))</pre><p>The logit function helps us transform the probability values (ranging from 0 to 1) into a continuous range of values. This is useful because it allows us to use linear regression techniques to model the relationship between predictor variables and the logit of the probability.</p><h3>Sigmoid Function</h3><p>The logistic function, also known as the sigmoid function, is the inverse of the logit function. It is used to transform the linear combination of predictor variables into a probability value between 0 and 1. Mathematically, the sigmoid function is defined as:</p><pre>sigmoid(x) = 1 / (1 + exp(-x))</pre><p>The sigmoid function takes the linear combination of predictor variables and maps it to a probability value between 0 and 1. This probability value can then be used to classify the outcome based on a threshold probability value (e.g., if the probability is greater than 0.5, classify the outcome as 1, otherwise classify it as 0).</p><p>We can plot this the sigmoid function Python as such:</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br><br>def sigmoid(x):<br>    return 1 / (1 + np.exp(-x))<br><br>x = np.linspace(-10, 10, 100)<br>y = sigmoid(x)<br><br>plt.plot(x, y)<br>plt.xlabel(&#39;x&#39;)<br>plt.ylabel(&#39;sigmoid(x)&#39;)<br>plt.title(&#39;Sigmoid Function&#39;)<br>plt.grid(True)<br>plt.show()</pre><figure><img alt="sigmoid function" src="https://cdn-images-1.medium.com/max/720/1*seauJgpwa7EOE-WyY0gogw.png" /></figure><h4>Estimating Coefficients</h4><p>In logistic regression, coefficients represent the relationship between the predictor variables and the logit of the probability of the outcome occurring. The coefficients are estimated using a technique called maximum likelihood estimation, which aims to find the values that maximize the likelihood of the observed data.</p><p>The maximum likelihood estimation process involves iteratively updating the coefficients to find the values that maximize the likelihood of the observed data. This is typically done using an optimization algorithm, such as <a href="https://en.wikipedia.org/wiki/Gradient_descent">gradient descent</a> or <a href="https://en.wikipedia.org/wiki/Newton%27s_method">Newton’s method</a>.</p><h4>Interpreting Coefficients</h4><p>Once we have estimated the coefficients, we can use them to understand how the predictor variables influence the outcome. In logistic regression, the coefficients tell us how the log-odds of the outcome change when the predictor variable increases by one unit, while keeping all other predictor variables constant.</p><p>For example, let’s say we have a coefficient of 0.5 for a predictor variable called “age.” This means that when a person’s age increases by one year, the log-odds of the outcome (e.g., making a purchase) increase by 0.5, assuming all other factors (e.g., browsing history, demographic information) remain the same. The log-odds can then be converted back to probabilities using the sigmoid function, which helps us understand the likelihood of the outcome occurring.</p><h4>Making Predictions with Logistic Regression</h4><p>To predict outcomes using logistic regression, we follow these steps:</p><p><strong>1. Combine predictor variables and coefficients</strong>: We multiply each predictor variable by its corresponding coefficient and add them together. This is called the linear combination of predictor variables and coefficients.</p><p><strong>2. Calculate the probability</strong>: We use the sigmoid function to convert the linear combination from step 1 into a probability value between 0 and 1. This probability represents the likelihood of the outcome occurring (e.g., making a purchase).</p><p><strong>3. Classify the outcome</strong>: We decide on a threshold probability value, often 0.5, to classify the outcome. If the probability calculated in step 2 is greater than the threshold, we predict the outcome as 1 (e.g., the customer will make a purchase). If the probability is less than or equal to the threshold, we predict the outcome as 0 (e.g., the customer will not make a purchase).</p><p>By following these steps, we can use logistic regression to make predictions for binary outcomes based on the predictor variables and their coefficients.</p><h3>Example with Actual Data</h3><p>Consider a logistic regression model that predicts whether a customer will make a purchase based on their age and income. The model estimates the probability of a purchase occurring given the customer’s age and income, and classifies the customer as a buyer or non-buyer based on a threshold probability value.</p><p>Suppose we have the following data:</p><pre>| Age | Income | Purchased |<br>|-----|--------|-----------|<br>| 25  | 50000  | 0         |<br>| 30  | 60000  | 0         |<br>| 35  | 70000  | 1         |<br>| 40  | 80000  | 1         |</pre><p>Using logistic regression, we can fit a model to this data and predict the probability of a purchase for new customers based on their age and income.</p><p>To do this, the code in Python is as simple as:</p><pre>import pandas as pd<br>from sklearn.linear_model import LogisticRegression<br><br># Load data (assume we have this saved in a csv file)<br>data = pd.read_csv(&#39;customer_data.csv&#39;)<br><br># Define features and target variable<br>X = data[[&#39;Age&#39;, &#39;Income&#39;]]<br>y = data[&#39;Purchased&#39;]<br><br># Fit logistic regression model<br>model = LogisticRegression()<br>model.fit(X, y)<br><br># Predict probability of purchase for new customers<br>new_customer = [[25, 50000]] # example new customer (age 25 &amp; income 50000)<br><br>prob_purchase = model.predict_proba(new_customer)[:,1]<br><br>print(&#39;Probability of purchase:&#39;, prob_purchase)</pre><h3>Assumptions of Logistic Regression</h3><p>Logistic regression makes several key assumptions:</p><ul><li><strong>Linear relationship</strong>: Assumes a linear relationship between the predictor variables and the logit of the outcome variable.</li><li><strong>Independence of predictor variables</strong>: Assumes that the predictor variables are independent and that there is no multicollinearity — meaning the predictor variables are not highly correlated with each other.</li><li><strong>Binary outcome variable</strong>: Assumes that the outcome variable is binary (i.e., it has two possible values).</li></ul><p>If any of these assumptions are violated, the model may not perform well. However, methods do exist for handling multiclass logistic regressions (i.e., when the outcome variable has more than two possible values) and for dealing with non-linear relationships between the predictor variables and the outcome variable. I’ll discuss them in a future post.</p><h3>Model Evaluation and Performance Metrics</h3><p>When evaluating the performance of a logistic regression model, it’s important to consider metrics beyond just accuracy, as accuracy can be misleading in certain situations, such as imbalanced datasets. Some common performance metrics for logistic regression include:</p><p><strong>1. Precision</strong>. The proportion of true positive predictions among all positive predictions. Optimize for precision when the cost of false positives is high (e.g., convicting someone of a crime; it’s better to let a guilty person go free than to convict an innocent person).</p><p><strong>2. Recall</strong>. The proportion of true positive predictions among all actual positives. Optimize for recall when the cost of false negatives is high (e.g., diagnosing a disease; it’s better to diagnose a healthy person as sick than to miss a sick person).</p><p><strong>3. F1 score</strong>. The harmonic mean of precision and recall, providing a balanced measure of both metrics.</p><p><strong>4. Confusion Matrix</strong>. A table that shows the number of true positives, true negatives, false positives, and false negatives for a classification model. It helps to visualize the performance of the model and identify any potential issues.</p><p><strong>5. ROC-AUC Score</strong>. The area under the Receiver Operating Characteristic (ROC) curve, which plots the true positive rate (recall) against the false positive rate. A higher ROC-AUC score indicates better model performance.</p><p>If you’re not sure where to start, a good starting point is to calculate the <strong>F1 score</strong>, which provides a balanced measure of both precision and recall. It’s also worth plotting the confusion matrix to help you visualize the performance of the model and identify any potential issues. Once you’re comfortable with these metrics, you can explore other metrics like ROC-AUC score to further evaluate your model.</p><p>Here’s some sample Python code using scikit-learn to calculate the F1 score and plot the confusion matrix:</p><pre># Load the dataset<br>data = load_breast_cancer()<br>X = data.data<br>y = data.target<br><br># Split the dataset into training and testing sets<br>X_train, X_test, y_train, y_test = train_test_split(<br>  X, y, test_size=0.2)<br><br># Train the logistic regression model<br>model = LogisticRegression(max_iter=5000)<br>model.fit(X_train, y_train)<br><br># Make predictions on the test set<br>y_pred = model.predict(X_test)<br><br># Calculate F1 score<br>f1 = f1_score(y_test, y_pred)<br>print(f&quot;F1 Score: {f1}&quot;)<br>print()<br><br># Plot confusion matrix<br>cm = confusion_matrix(y_test, y_pred, normalize=&#39;true&#39;)<br>disp = ConfusionMatrixDisplay(confusion_matrix=cm)<br>disp.plot();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*9vdLmjWLyu9fDTQ6RmPWCA.png" /></figure><p>By starting with the F1 score and confusion matrix, you can gain a better understanding of your model’s performance and gradually explore other metrics as needed.</p><p>ROC-AUC score is particularly useful because it evaluates your model based on the <em>probabilities </em>it assigns to each prediction. Rather judging your model’s binary predictions, it looks at the probability of each prediction and evaluates the model based on how well it can differentiate between classes. This is especially useful when dealing with imbalanced datasets.</p><h3>Conclusion</h3><p>Logistic regression has numerous real-world applications, including:</p><ul><li><strong>Predicting customer churn</strong>: Logistic regression can be used to predict whether a customer will cancel their subscription based on their usage patterns and demographic information.</li><li><strong>Medical diagnosis</strong>: Logistic regression can be used to predict the presence or absence of a disease based on patient symptoms and test results.</li><li><strong>Spam detection</strong>: Logistic regression can be used to classify emails as spam or not spam based on the content and metadata of the email.</li></ul><p>You’re certain to perform many of them throughout your data science career; they’re favored because they’re relatively simple to implement and interpret, and — perhaps just as importantly — they’re fast to train and make predictions with (especially when compared to more complex models).</p><p>In this first part of this series, we’ve explored the basics of logistic regression, discussed its assumptions, and seen a brief example with actual data inside Python. In the next part, we’ll delve into regularization in logistic regression, including L1 and L2 regularization, convexity, and choosing the appropriate regularization technique.</p><p>My complete series on logistic regression:</p><ul><li><strong>Logistic Regression: An Introduction</strong></li><li><a href="https://medium.com/@vincefav/regularization-in-logistic-regression-14b50d7cc31">Regularization in Logistic Regression</a></li><li><a href="https://medium.com/@vincefav/advanced-techniques-in-logistic-regression-part-1-ebf945686958">Advanced Techniques in Logistic Regression — Part 1</a></li><li><a href="https://medium.com/@vincefav/advanced-techniques-for-logistic-regression-and-classification-part-2-daaa968d54c">Advanced Techniques for Logistic Regression and Classification — Part 2</a></li><li><a href="https://medium.com/@vincefav/mastering-logistic-regression-in-python-with-statsmodels-52bd7cc77af4">Mastering Logistic Regression in Python with StatsModels</a></li><li><a href="https://colab.research.google.com/drive/1GwdYQn9PW_XPKErp7biz6UprL9a-oln-?usp=sharing">Colab Notebook</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=141c1f627adf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>