It may be that the order of your X_train data is wrong. Try to sort them out. For instance, if X_train is just a list of numbers, you could say:

X_train.sort()
Answer from Neb on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › machine learning › ml-logistic-regression-using-python
Logistic Regression using Python - GeeksforGeeks
February 10, 2026 - Logistic Regression is a widely used supervised machine learning algorithm used for classification tasks. In Python, it helps model the relationship between input features and a categorical outcome by estimating class probabilities, making it ...
🌐
Statology
statology.org › home › how to plot a logistic regression curve in python
How to Plot a Logistic Regression Curve in Python
November 12, 2021 - #define the predictor variable and the response variable x = data['balance'] y = data['default'] #plot logistic regression curve with black points and red line sns.regplot(x=x, y=y, data=data, logistic=True, ci=None), scatter_kws={'color': 'black'}, line_kws={'color': 'red'})
Discussions

python - Sklearn logistic regression, plotting probability curve graph - Stack Overflow
I'm trying to create a logistic regression similar to the ISLR's example, but using python instead data=pd.read_csv("data/Default.csv") #first we'll have to convert the strings "No" and "Yes" to More on stackoverflow.com
🌐 stackoverflow.com
Best way to plot and rank logistic regression coefficients?
For plotting coefficients, something like this might look good: coefficient plot in python . For deciding what to keep in the model, you should look at step-wise model selection with AIC and BIC. This process is implemented in R . Scikit-learn has something similar it seems. See this discussion on stackexchange . More on reddit.com
🌐 r/learnpython
3
1
January 11, 2018
Trouble producing logistic regression plot
Hello, statistically, when you are looking at the first graph, it's clearly a visual scatterplot. In your second example, there is a huge visual change. You have essentiallly graphed a series of vertical lines. I'm assuming there is no regression line appearing because the datapoints are no longer cohesive. It's currently looking for a relationship between the age categories, but as you can see, there isn't one. They are very clearly separated along distinct, vertical lines. You're going to have to create the regession line on the full data, not the age categories. I'm certainly not a pro, but I would approach this one of two ways. Option 1: If you truly want the regression line from the first graph and the data points looking like they do in the second graph, then I'd graph them separate and add them together. Graph your data points the way you want them (like you did in the second graph). Then use the method you used in the first graph to created the regression line the way you want it, but leave out the datapoints. Use theme to make your background, lables, axis ticks, title, etc. transparent. Then combine. There's a few ways to combine. I've had the best success with grob. Option 2: Annotate a line when you create the graph. GraphName + annotate("segment", x = 0, xend = 100, y = 0, yend = 85, colour = "dark red" ) where x= and y= are teh coordiate for the leftmost point of your annotated line. and xend= and yend= are the coordinate for the rightmost point of your annotated line. This will produce a completed straight line, so it might not be what you are looking for. More on reddit.com
🌐 r/Rlanguage
1
0
January 19, 2023
Comprehensive Guide on Logistic Regression
Wow very in depth explanations guys. Reading through the PCA article now. More on reddit.com
🌐 r/learnmachinelearning
10
72
July 27, 2022
🌐
NBShare
nbshare.io › notebook › 415235001 › Understanding-Logistic-Regression-Using-Python
Understanding Logistic Regression Using Python
The plot_data() function creates a scatter plot. In the below code, we are invoking the function plot_data() which will create the scatter plot. ... We can now try to fit a curve to this data using the logistic function that we created in the beginning of this post.
🌐
Real Python
realpython.com › logistic-regression-python
Logistic Regression in Python – Real Python
June 26, 2023 - You’ll find useful information ... and logistic regression implementation. If you need functionality that scikit-learn can’t offer, then you might find StatsModels useful. It’s a powerful Python library for statistical analysis. You can find more information on the official website. Finally, you’ll use Matplotlib to visualize the results of your classification. This is a Python library that’s comprehensive and widely used for high-quality plotting...
Find elsewhere
🌐
Medium
medium.com › @ginoasuncion › visualizing-logistic-regression-results-using-a-forest-plot-in-python-bc7ba65b55bb
Visualizing logistic regression results using a forest plot in Python | by Xavier Eugenio Asuncion | Medium
November 8, 2021 - To visualize the logistic regression results, I used a forest plot (or blobbogram). Specifically, the forest plot was used to graphically represent the odds ratios and their corresponding confidence intervals.
🌐
SciPython
scipython.com › blog › plotting-the-decision-boundary-of-a-logistic-regression-model
Plotting the decision boundary of a logistic regression model
September 17, 2020 - import numpy as np import matplotlib.pyplot as plt import sklearn.linear_model plt.rc('text', usetex=True) pts = np.loadtxt('linpts.txt') X = pts[:,:2] Y = pts[:,2].astype('int') # Fit the data to a logistic regression model. clf = sklearn.linear_model.LogisticRegression() clf.fit(X, Y) # Retrieve the model parameters. b = clf.intercept_[0] w1, w2 = clf.coef_.T # Calculate the intercept and gradient of the decision boundary. c = -b/w2 m = -w1/w2 # Plot the data and the classification with the decision boundary.
🌐
scikit-learn
scikit-learn.org › 1.5 › auto_examples › linear_model › plot_logistic.html
Logistic function — scikit-learn 1.5.2 documentation
# Code source: Gael Varoquaux # License: BSD 3 clause import matplotlib.pyplot as plt import numpy as np from scipy.special import expit from sklearn.linear_model import LinearRegression, LogisticRegression # Generate a toy dataset, it's just a straight line with some Gaussian noise: xmin, xmax = -5, 5 n_samples = 100 np.random.seed(0) X = np.random.normal(size=n_samples) y = (X > 0).astype(float) X[X > 0] *= 4 X += 0.3 * np.random.normal(size=n_samples) X = X[:, np.newaxis] # Fit the classifier clf = LogisticRegression(C=1e5) clf.fit(X, y) # and plot the result plt.figure(1, figsize=(4, 3)) p
🌐
Kaggle
kaggle.com › code › aakritsinghal › logistic-regression-visualisation
Logistic Regression Visualisation
Checking your browser before accessing www.kaggle.com · Click here if you are not automatically redirected after 5 seconds
🌐
scikit-learn
scikit-learn.org › stable › modules › generated › sklearn.linear_model.LogisticRegression.html
LogisticRegression — scikit-learn 1.8.0 documentation
Gallery examples: Probability Calibration curves Plot classification probability Column Transformer with Mixed Types Pipelining: chaining a PCA and a logistic regression Feature transformations wit...
🌐
University of Washington
faculty.washington.edu › otoomet › machinelearning-py › logistic-regression.html
Chapter 11 Logistic Regression | Machine learning in python
\end{equation*}\] Note that the formula specifies just the link function \(\eta\), the logistic function part of the model is already embedded in smf.logit. We can see the estimated values with ... This indicates that our example plot above, using values 0 and -0.1, was fairly close. ... The output is similar to that of linear regression, with certain differences that are appropriate for logistic regression.
🌐
Ajaytech
ajaytech.co › python-logistic-regression
Python Logistic Regression - Ajay Tech
June 18, 2019 - How exactly is the logistic regression similar to linear regression ? Like so. To understand this better, let’s plot the log of odds between a probabilty value of 0 and 1. import numpy as np x = np.linspace (0, 0.999, num=100) y = np.log (x/(1-x) ) c:\program files (x86)\python37-32\lib\s...
🌐
Medium
medium.com › pursuitnotes › logistic-regression-model-in-9-steps-with-python-dbfd924f9305
Logistic Regression Model in 9 Steps with Python | by Samet Girgin | PursuitOfData | Medium
December 10, 2021 - Lets only use random_state=0 #We create a classifier object of LR classclassifier= LogisticRegression(random_state=0)#Fit logistic regression model to the training set (X_train and #y_train)classifier.fit(X_train, y_train)#6 Predicting the Test set results #Using predict method for the classifier object and put X_test for #argument y_pred = classifier.predict(X_test)
🌐
DataCamp
datacamp.com › tutorial › understanding-logistic-regression-python
Python Logistic Regression Tutorial with Sklearn & Scikit | DataCamp
August 11, 2024 - In this tutorial, you'll learn about Logistic Regression in Python, its basic properties, and build a machine learning model on a real-world application.
🌐
Reddit
reddit.com › r/learnpython › best way to plot and rank logistic regression coefficients?
r/learnpython on Reddit: Best way to plot and rank logistic regression coefficients?
January 11, 2018 -

Hi I am a beginner in coding in python and machine learning and I am trying to learn about what goes on under the hood of logistic regression and making it run in python. I have been tasked with plotting and ranking the weights/coefficients of logistic regression below in order to remove features with the least impact from the code. But, whilst I've added a basic plot it doesn't help me rank the coefficients/thetas. Any help pointing in the right direction would be appreciated.

This is also using the wisconin breast cancer dataset (https://www.kaggle.com/uciml/breast-cancer-wisconsin-data)

import matplotlib.pyplot as plt
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split

df = pd.read_csv("cancerdata.csv")
X = df.values[:,2:-1].astype('float64')
X = (X - np.mean(X, axis =0)) /  np.std(X, axis = 0)


X = np.hstack([np.ones((X.shape[0], 1)),X])
X = MinMaxScaler().fit_transform(X)
Y = df["diagnosis"].map({'M':1,'B':0})
Y = np.array(Y)
X_train,X_test,Y_train,Y_test = 
train_test_split(X,Y,test_size=0.25)


def Sigmoid(z):
    return 1/(1 + np.exp(-z))

def Hypothesis(theta, x):   
    return Sigmoid(x @ theta) 

def Cost_Function(X,Y,theta,m):
    hi = Hypothesis(theta, X)
    _y = Y.reshape(-1, 1)
    J = 1/float(m) * np.sum(-_y * np.log(hi) - (1-_y) * np.log(1-hi))
    return J

def Cost_Function_Derivative(X,Y,theta,m,alpha):
    hi = Hypothesis(theta,X)
    _y = Y.reshape(-1, 1)
     J = alpha/float(m) * X.T @ (hi - _y)
    return J

def Gradient_Descent(X,Y,theta,m,alpha):
new_theta = theta - 
Cost_Function_Derivative(X,Y,theta,m,alpha)
    return new_theta

def Accuracy(theta):
    correct = 0
    length = len(X_test)
    prediction = (Hypothesis(theta, X_test) > 0.5)
    _y = Y_test.reshape(-1, 1)
    correct = prediction == _y
    my_accuracy = (np.sum(correct) / length)*100
    print ('LR Accuracy %: ', my_accuracy)

def Logistic_Regression(X,Y,alpha,theta,num_iters):
    m = len(Y)
    for x in range(num_iters):
        new_theta = 
Gradient_Descent(X,Y,theta,m,alpha)
        theta = new_theta
        if x % 100 == 0:
    Accuracy(theta)
    plt.plot(theta)
    plt.show()
ep = .012

initial_theta = np.random.rand(X_train.shape[1],1) * 2 * ep - ep
alpha = 0.5
iterations = 2000


Logistic_Regression(X_train,Y_train,alpha,initial_theta,iterations)
🌐
Towards Data Science
towardsdatascience.com › home › latest › assumptions of logistic regression, clearly explained
Assumptions of Logistic Regression, Clearly Explained | Towards Data Science
March 5, 2025 - In this article, we explore the key assumptions of logistic regression with theoretical explanations and practical Python implementation of the assumption checks.
🌐
Arab Psychology
scales.arabpsychology.com › home › stats › how to easily plot a logistic regression curve in python
How To Easily Plot A Logistic Regression Curve In Python
December 2, 2025 - It simplifies the complexity often associated with raw Matplotlib commands, especially when fitting and plotting regression models. For plotting a logistic fit, Seaborn includes a dedicated function: regplot.