保留正文与补采附件。源页面当前未重新核验;具体限制见交付清单。

Revisit consent button We value your privacy We use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking "Accept All", you consent to our use of cookies. Customise Reject All Accept All Customise Consent Preferences We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below. The cookies that are categorised as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more NecessaryAlways Active Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

Functional Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

Analytics Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

Performance Performance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.

Advertisement Advertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.

Uncategorised Other uncategorised cookies are those that are being analysed and have not been classified into a category as yet. No cookies to display. Reject All Save My Preferences Accept All Toggle SearchToggle Mobile Navigation Publish AI, ML & data-science insights to a global community of data professionals. Sign inSubmit an Article LatestEditor's PicksNewsletterShipAI


Write For TDS LinkedInXToggle Search Data Science

Logistic Regression

Or how I learned to love the sigmoid "squishification" function for categorical data classification James Andrew Godwin April 13, 20215 min read Logistic Regression | Photo by Denise Bossarte Logistic Regression | Photo by Denise Bossarte This article is a brief continuation of my regression series. So far the regression examples I have been illustrating have been numeric, of numbers: predicting a continuous variable. With the Galton family height dataset, we were predicting children's height - a continuously varying parameter. Yet, note how a regression line fails to fit a binary outcome, a classification example: Line of best fit for binary outcomes Line of best fit for binary outcomes In the above example, there appears to be a threshold affecting the classification outcomes. It does not make sense to have a continuous regression line for this data. Why does it not make sense? Look at the two dependent (y) variables: they take on one of two values: 0 and 1. There is no value for 0.25 or 0.5, just those two extrema. This means that for this classification problem we want a function that takes as an input, or a series of inputs, and gives us a probability of it being one of the two classes: namely 0 and 1. We can give any arbitrary label to these classes: yes or no, cat or not cat, send a promotional email or do not send a promotional email, sales lead or unlikely sales lead. Logistic regression is a powerful tool for data scientists and machine learning engineers alike. I would say, for sanity checks, that it should be the baseline model for classification purposes - one that is compared against more complex models (like PCR, neural networks, etc).

History

Logistic regression

To get to logistic regression, we first begin with our classic regression example: Classic regression Classic regression To develop a model for classification we will borrow the sigmoid function from math, commonly expressed below as: Sigmoid formula Sigmoid formula Rearranging and substituting into the regression: Formula for logistic regression Formula for logistic regression What this family of functions does is give a probability of assigning the observation to the target class. Once the logistic regression function assigns a probability, this requires the model to be fit and trained on the dataset, an example further down, the data point is projected into a class based on the probability value. For probability values greater than 0.5 the value is projected onto 1, for us the target class, and for probability values less than 0.5, they are projected onto the 0 class, or not the target class. A standard sigmoid function looks as follows: Standard logistic function | Photo source Wikipedia. Standard logistic function | Photo source Wikipedia.) This transforms our original dataset regression line into: The inflection point is at 0.5 The inflection point is at 0.5

What just happened?

This "s" shape is a powerful tool for classification purposes. I like to think that given probability value output for a given observation, say 0.36, that the logistic regression is "squishing" the probability down to binary value. Interpreting this, the model is saying that there is only a 36% chance that the given observation belongs to the target class the model was trained on - let us say that is 1. Meaning that there is a 1 - .36 or 64% chance that this observation does not belong to the target class, so it is labeled as 0 ->the observation is projected down to the dependent variable outcome label of 0. The logistic regression line is similar to our previous regression examples, but we interpret the output as a probability of assigning the data point to the target class. The most common flavor of logistic regression is binary logistic regression, but multinomial logit models do exist for multiclass regression analysis. N.B: It is technically possible to achieve a value of 0.5, but vanishingly small. Regardless, the algorithm you are using will have some predefined instruction on how to classify this edge case.

Python example: Logistic regression

For illustrative purposes, I will be using the famous iris dataset included with sklean to demonstrate the classification power in the following Jupyter notebook cells: text

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score

text

%matplotlib inline

Create a df and transform all the raw data into a format familiar to sklearn: text

from sklearn.datasets import load_iris
iris = load_iris()
df = pd.DataFrame(data= np.c_[iris['data'], iris['target']],
 columns= ["sepel_length_cm", "sepal_width_cm",
 "petal_length_cm", "petal_width_cm", "target"])

text

df.head()

Data is well imported Data is well imported text

df.describe()

Basic summary statistics Basic summary statistics The data set contains the true labels, and we can see how nice and separable the three classes are: text

sns.pairplot(df, height=2.5, hue='target')
plt.show()

The classifications for the three flower types based on their measurables The classifications for the three flower types based on their measurables text

df['target'].value_counts()

Note how we have three classes of flowers, each with 50 observations. This dataset is very well balanced. text

X, y = load_iris(return_X_y=True)

text

X[:5]

text

y[:5]

The above five flowers are all of the 0 class. text

from sklearn.linear_model import LogisticRegression

text

# instantiate the model and fit
log = LogisticRegression(multi_class='warn', solver='warn')
log_reg = log.fit(X, y)

text

log_reg

text

# score the model
log.score(X, y)

As we can see, this is a very good score for the model! Next, I will talk about Time Series Analysis! Find me on Linkedin Physicist cum Data Scientist- Available for new opportunity | SaaS | Sports | Start-ups | Scale-ups

Register Now to Continue Reading

Unlock Towards Data Science with a Free Account

All articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more. Register for freeSign in to your account


Written By

James Andrew Godwin

See all from James Andrew Godwin Data ScienceLogistic RegressionMachine LearningPythonTowards Data Science Share This Article

Towards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program. Write for TDS

Related Articles

What is Data Science? A Legacy Business' Guide in Big Data Analytics

Programming New data is created every single second - a ton of it. This data comes from your smartphone that tracks your movements, your web browser... Steve Sangapu July 10, 20208 min read

Building a Video Game Recommender System with FastAPI, PostgreSQL, and Render: Part 2

Data Science Deploying a FastAPI + PostgreSQL recommender system as a web application on Render Lucas See September 25, 202515 min read

Work with Alteryx from UiPath

Data Science How to make API calls to your Alteryx workflows from UiPath Deepak Krishnamurthy April 3, 20223 min read

How to Perform Sentiment Analysis on Earnings Call of Companies

Artificial Intelligence Deploying Sentiment Analysis with Python and AI to analyze the Earnings Call of Companies Bharath K February 23, 202210 min read

Crime and Punishment in the Inner City

Data Science The burden of poverty in Kansas City goes deeper than income and housing Scott Haluck December 23, 20204 min read

How to use PyCaret - the library for low-code ML

Artificial Intelligence Train, visualize, evaluate, interpret, and deploy models with minimal code. Amol Mavuduru February 25, 202110 min read

Intergenerational Mobility in the US - Exploratory Data Analysis (3/5)

Data Science This series was written together with Ibukun Aribilola and Valdrin Jonuzi as part of the Data Science for Social Good tutorial. Ang Li-Lian April 22, 202210 min read

Few DON'Ts for Data Scientists

Machine Learning Many Data Scientists focuses on algorithms and mathematics but fail to learn an important skill - communication. Roman Orac November 19, 20206 min read

How to deploy Azure machine learning models as a secure endpoint

Machine Learning Learn how to build an MLOps pipeline with Azure API management to deploy models as secure endpoints René Bremer October 31, 20215 min read

Your home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals. Subscribe to Our NewsletterWrite For TDS•About•Advertise•Privacy Policy•Terms of Use © Insight Media Group, LLC 2026•The New Stack•roadmap.sh•Creator Network

Recommended Articles

Close