# Logistic Regression With Non-Linear Boundary Demo¶

☝Before moving on with this demo you might want to take a look at:

Logistic regression is the appropriate regression analysis to conduct when the dependent variable is dichotomous (binary). Like all regression analyses, the logistic regression is a predictive analysis. Logistic regression is used to describe data and to explain the relationship between one dependent binary variable and one or more nominal, ordinal, interval or ratio-level independent variables.

Logistic Regression is used when the dependent variable (target) is categorical.

For example:

• To predict whether an email is spam (1) or (0).
• Whether online transaction is fraudulent (1) or not (0).
• Whether the tumor is malignant (1) or not (0).

Demo Project: In this example we will try to classify microchips into to categories (valid and invalid) based on two artifical parameters param_1 and param_2.

In :
# To make debugging of logistic_regression module easier we enable imported modules autoreloading feature.
# By doing this you may change the code of logistic_regression library and all these changes will be available here.

import sys
sys.path.append('../..')


### Import Dependencies¶

• pandas - library that we will use for loading and displaying the data in a table
• numpy - library that we will use for linear algebra operations
• matplotlib - library that we will use for plotting the data
• logistic_regression - custom implementation of logistic regression
In :
# Import 3rd party dependencies.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# Import custom logistic regression implementation.


In this demo we will use artificial dataset in which param_1 and param_2 produce non-linear decision boundary (see the plot below).

In :
# Load the data.

# Print the data table.

Out:
param_1 param_2 validity
0 0.051267 0.699560 1
1 -0.092742 0.684940 1
2 -0.213710 0.692250 1
3 -0.375000 0.502190 1
4 -0.513250 0.465640 1
5 -0.524770 0.209800 1
6 -0.398040 0.034357 1
7 -0.305880 -0.192250 1
8 0.016705 -0.404240 1
9 0.131910 -0.513890 1

### Plot the Data¶

Let's plot the data on 2D-plane and split it by two clasess (valid and invalid) to see the distribution.

In :
# Supported set of validities.
validities = [0, 1]

# Dataset parameters that we will take into account.
x_axis = 'param_1'
y_axis = 'param_2'

# Scatter the data on the plot for each validity class separatelly.
for validity in validities:
plt.scatter(
data[x_axis][data['validity'] == validity],
data[y_axis][data['validity'] == validity],
label=validity
)

# Plot the data.
plt.xlabel(x_axis)
plt.ylabel(y_axis)
plt.title('Microchips Tests')
plt.legend()
plt.show() ### Prepare the Data for Training¶

Before we move on with training our logistic model let's extract the data from Pandas data frame and shape training features set and labels set correctly.

In :
# Get the number of training examples.
num_examples = data.shape

# Extract and shape features.
x_train = data[[x_axis, y_axis]].values.reshape((num_examples, 2))

# Extract and shape labels.
y_train = data['validity'].values.reshape((num_examples, 1))


### Init and Train Logistic Regression Model¶

☝🏻This is the place where you might want to play with model configuration.

• polynomial_degree - this parameter will allow you to add additional polynomial features of certain degree. More features - more curved the line will be.
• max_iterations - this is the maximum number of iterations that gradient descent algorithm will use to find the minimum of a cost function. Low numbers may prevent gradient descent from reaching the minimum. High numbers will make the algorithm work longer without improving its accuracy.
• regularization_param - parameter that will fight overfitting. The higher the parameter, the simplier is the model will be.
• polynomial_degree - the degree of additional polynomial features (x1^2 * x2, x1^2 * x2^2, ...). This will allow you to curve the predictions.
• sinusoid_degree - the degree of sinusoid parameter multipliers of additional features (sin(x), sin(2*x), ...). This will allow you to curve the predictions by adding sinusoidal component to the prediction curve.
In :
# Set up linear regression parameters.
max_iterations = 100000  # Max number of gradient descent iterations.
regularization_param = 0  # Helps to fight model overfitting.
polynomial_degree = 5  # The degree of additional polynomial features.
sinusoid_degree = 0  # The degree of sinusoid parameter multipliers of additional features.

# Init logistic regression instance.
logistic_regression = LogisticRegression(x_train, y_train, polynomial_degree, sinusoid_degree)

# Train logistic regression.
(thetas, costs) = logistic_regression.train(regularization_param, max_iterations)

# Rename the columns for each theta.
columns = []
for theta_index in range(0, thetas.shape):
columns.append('Theta ' + str(theta_index));

pd.DataFrame(thetas, index=['VALID', 'INVALID'], columns=columns)

Out:
Theta 0 Theta 1 Theta 2 Theta 3 Theta 4 Theta 5 Theta 6 Theta 7 Theta 8 Theta 9 ... Theta 13 Theta 14 Theta 15 Theta 16 Theta 17 Theta 18 Theta 19 Theta 20 Theta 21 Theta 22
VALID -2.024052 1.660125 -1.042190 1.660125 -1.042190 -3.345081 11.635574 -10.209539 -19.784433 -29.263600 ... -0.443705 37.384232 1.548052 40.476004 16.795521 24.197483 -0.966907 33.948141 46.700557 -22.072182
INVALID 2.028452 -1.614655 1.083132 -1.614655 1.083132 3.439305 -11.411377 10.258364 19.310634 28.477962 ... -0.423851 -38.205306 -2.021708 -40.536997 -16.190337 -22.698874 2.868809 -32.068645 -45.901514 22.308492

2 rows × 23 columns

The plot below illustrates how the cost function value changes over each iteration. You should see it decreasing.

In case if cost function value increases it may mean that gradient descent missed the cost function minimum and with each step it goes further away from it.

From this plot you may also get an understanding of how many iterations you need to get an optimal value of the cost function.

In :
# Draw gradient descent progress for each label.
labels = logistic_regression.unique_labels

plt.plot(range(len(costs)), costs, label=labels)
plt.plot(range(len(costs)), costs, label=labels)

plt.ylabel('Cost')
plt.legend()
plt.show() ### Calculate Model Training Precision¶

Calculate how many flowers from the training set have been guessed correctly.

In :
# Make training set predictions.
y_train_predictions = logistic_regression.predict(x_train)

# Check what percentage of them are actually correct.
precision = np.sum(y_train_predictions == y_train) / y_train.shape * 100

print('Training Precision: {:5.4f}%'.format(precision))

Training Precision: 88.9831%


### Draw Decision Boundaries¶

Let's build our decision boundaries. These are the lines that distinguish classes from each other. This will give us a pretty clear overview of how successfull our training process was. You should see clear distinguishment of three sectors on the data plain.

In :
# Get the number of training examples.
num_examples = x_train.shape

# Set up how many calculations we want to do along every axis.
samples = 150

# Generate test ranges for x and y axis.
x_min = np.min(x_train[:, 0])
x_max = np.max(x_train[:, 0])

y_min = np.min(x_train[:, 1])
y_max = np.max(x_train[:, 1])

X = np.linspace(x_min, x_max, samples)
Y = np.linspace(y_min, y_max, samples)
Z = np.zeros((samples, samples))

# z axis will contain our predictions. So let's get predictions for every pair of x and y.
for x_index, x in enumerate(X):
for y_index, y in enumerate(Y):
data = np.array([[x, y]])
Z[x_index][y_index] = logistic_regression.predict(data)

# Now, when we have x, y and z axes being setup and calculated we may print decision boundaries.
positives = (y_train == 1).flatten()
negatives = (y_train == 0).flatten()

plt.scatter(x_train[negatives, 0], x_train[negatives, 1], label='0')
plt.scatter(x_train[positives, 0], x_train[positives, 1], label='1')

plt.contour(X, Y, Z)

plt.xlabel('param_1')
plt.ylabel('param_2')
plt.title('Microchips Tests')
plt.legend()

plt.show() 