how to do logistic regression in python

Logistic Regression is a supervised learning algorithm used for binary classification problems. It predicts the probability of an event occurring by fitting the data to a logistic curve. In Python, scikit-learn library provides a simple and efficient function for logistic regression.

Here's an example code that demonstrates how to perform logistic regression using scikit-learn:

main.py
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# load data into a pandas dataframe
data = pd.read_csv('data.csv')

# split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(
    data.drop('target_column', axis=1), data['target_column'], test_size=0.2)

# create a logistic regression model
model = LogisticRegression()

# train the model on the training data
model.fit(X_train, y_train)

# predict the target values for the test set
y_pred = model.predict(X_test)

# calculate the accuracy of the model on the test set
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy}")
756 chars
25 lines

In the above code, we first load the data into a pandas dataframe. We then split the data into training and testing sets using the train_test_split function. We create a logistic regression model using the LogisticRegression class and train the model using the fit method. Finally, we predict the target values for the test set using the predict method and calculate the accuracy of the model using the accuracy_score function.

gistlibby LogSnag