# Logistic Regression

I find the name logistic regression annoying. We don’t normally use logistic regression for anything other than classification; but statistics coined the name long ago.

Despite the name, logistic regression is incredibly useful. Instead of optimising the error of the distance like we did in standard linear regression, we can frame the problem probabilistically. Logistic regression attempts to separate classes based upon the probability that an observation belongs to a class.

# Usual imports
import os
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import display
from sklearn import datasets
from sklearn import preprocessing

# import some data to play with
feat = iris.feature_names
X = iris.data[:, :2]  # we only take the first two features. We could
# avoid this ugly slicing by using a two-dim dataset
y = iris.target
y[y != 0] = 1 # Only use two targets for now
colors = "bry"

# standardize
X = preprocessing.StandardScaler().fit_transform(X)


Of course, SKLearn has an implementation of logistic regression and it uses the usual fit API.

from sklearn.linear_model import LogisticRegression
log_reg = LogisticRegression().fit(X, y)


Because I want to show probability contours, the plotting code is a bit more complicated than usual.

# Create a grid of points then calculate the probability at each point. This creates a "mesh" of points.
x0, x1 = np.meshgrid(
np.linspace(-3, 3, 500).reshape(-1, 1),
np.linspace(-3, 3, 200).reshape(-1, 1),
)
X_new = np.c_[x0.ravel(), x1.ravel()]

y_proba = log_reg.predict_proba(X_new)

plt.scatter(X[y == 0, 0], X[y == 0, 1],
color='red', marker='o', label='setosa')
plt.scatter(X[y != 0, 0], X[y != 0, 1],
color='blue', marker='x', label='not setosa')

zz = y_proba[:, 1].reshape(x0.shape)
contour = plt.contour(x0, x1, zz, cmap=plt.cm.brg)

left_right = np.array([-3, 3])
boundary = -(log_reg.coef_ * left_right + log_reg.intercept_) / log_reg.coef_

plt.clabel(contour, inline=1, fontsize=12)
plt.plot(left_right, boundary, "k--", linewidth=3)
plt.xlabel(feat)
plt.ylabel(feat)
plt.legend(loc='upper left')
plt.axis([-3,3,-3,3])
plt.show() Note the probability estimates in the contours. This is an incredibly useful trait. To provide class estimates with an estimate to show how likely that observation is to really be part of that class.

But always remember that these estimates are based upon a gaussian fit of the data. If the data isn’t representative or it isn’t normally distributed, then these estimates will be erroneous in some way.
{"ft_lang_label":"__label__en","ft_lang_prob":0.68701524,"math_prob":0.9884774,"size":2695,"snap":"2019-51-2020-05","text_gpt3_token_len":678,"char_repetition_ratio":0.10479376,"word_repetition_ratio":0.0,"special_character_ratio":0.26790354,"punctuation_ratio":0.19449541,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9993785,"pos_list":[0,1,2],"im_url_duplicate_count":[null,2,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2020-01-26T05:47:23Z\",\"WARC-Record-ID\":\"<urn:uuid:df049f89-75e1-44fe-b2c7-1451e5160d92>\",\"Content-Length\":\"11257\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:7712ea95-0718-43ca-8998-11f72a42ddf4>\",\"WARC-Concurrent-To\":\"<urn:uuid:ba37212d-9d58-477a-83d1-5e130868052b>\",\"WARC-IP-Address\":\"13.249.44.21\",\"WARC-Target-URI\":\"https://trainingdatascience.com/workshops/logistic-regression/\",\"WARC-Payload-Digest\":\"sha1:Z3HIHDINOJKIIH3ZCJU4QO4U47TGT32O\",\"WARC-Block-Digest\":\"sha1:KJWOHOPO7MMG2UPZ5WRO64W33YHJ6HSB\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2020/CC-MAIN-2020-05/CC-MAIN-2020-05_segments_1579251687725.76_warc_CC-MAIN-20200126043644-20200126073644-00064.warc.gz\"}"}