Logistic Regression 101: A Beginner’s Guide with Python

Chang In Moon Chang In Moon #python#machine-learning#statistics

We will start by importing the necessary libraries and loading the data.

Logistic Regression is a popular statistical model that is often used for binary classification tasks. In this tutorial, we will learn how to implement Logistic Regression in Python using the scikit-learn library.

We will start by importing the necessary libraries and loading the data. The scikit-learn library provides several datasets that we can use for this tutorial. For this example, we will use the “Iris” dataset, which consists of 150 observations of iris flowers with four features: sepal length, sepal width, petal length, and petal width. The goal is to predict the species of the iris flower based on these features.

import pandas as pd
from sklearn.datasets import load_iris
# Load the Iris dataset
iris = load_iris()
# Create a DataFrame from the Iris data
df = pd.DataFrame(iris.data, columns=iris.feature_names)
# Add the target column to the DataFrame
df['target'] = iris.target
# Print the first 5 rows of the DataFrame
df.head()

The next step is to split the data into training and testing sets. We will use the training set to fit the model, and the testing set to evaluate its performance.

from sklearn.model_selection import train_test_split
# Split the data into a training set and a testing set
X = df.drop('target', axis=1)
y = df['target']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)

Now that we have our data ready, we can fit a Logistic Regression model to the training data. We will use the LogisticRegression class from the sklearn.linear_model module.

from sklearn.linear_model import LogisticRegression
# Create a Logistic Regression model
model = LogisticRegression()
# Fit the model to the training data
model.fit(X_train, y_train)

After fitting the model to the training data, we can use it to make predictions on the testing data. We can do this using the predict method of the model.

# Make predictions on the testing data
y_pred = model.predict(X_test)

Finally, we can evaluate the performance of the model using various metrics such as accuracy, precision, and recall. The sklearn.metrics module provides several functions for computing these metrics.

from sklearn.metrics import accuracy_score, precision_score, recall_score
# Calculate the accuracy of the model
accuracy = accuracy_score(y_test, y_pred)
# Calculate the precision of the model
precision = precision_score(y_test, y_pred, average='micro')
# Calculate the recall of the model
recall = recall_score(y_test, y_pred, average='micro')
# Print the results
print("Accuracy:", accuracy)
print("Precision:", precision)
print("Recall:", recall)

That’s it! You now know how to implement Logistic Regression in Python using the scikit-learn library. However, this is just the basic implementation of Logistic Regression. There are several parameters and options that you can adjust to improve the performance of the model.

For example, you can adjust the regularization strength of the model using the C parameter. By default, the C parameter is set to 1.0, which means that the model is not regularized. You can increase the value of C to increase the strength of the regularization, or decrease it to decrease the strength.

# Create a Logistic Regression model with a stronger regularization
model = LogisticRegression(C=10.0)
# Fit the model to the training data
model.fit(X_train, y_train)

You can also adjust the solver algorithm that is used to fit the model. By default, the solver parameter is set to “lbfgs”, which is a good choice for small datasets. However, for larger datasets, you may want to use a different solver such as “sag” or “liblinear”.

# Create a Logistic Regression model with the "sag" solver
model = LogisticRegression(solver='sag')
# Fit the model to the training data
model.fit(X_train, y_train)

There are many other parameters and options that you can adjust to improve the performance of the model. For a complete list of parameters and options, you can refer to the documentation of the LogisticRegression class in the scikit-learn library.

In conclusion, Logistic Regression is a powerful and widely-used tool for binary classification tasks. It is relatively simple to implement and interpret, and is robust to noise and outliers. By adjusting the various parameters and options, you can improve the performance of the model and achieve better results on your classification tasks.

Comments