Home > front end >  Matplotlib Plot curve logistic regression
Matplotlib Plot curve logistic regression

Time:10-05

I am trying to plot the trained curve in matplotlib. However I am getting this thing: enter image description here

The scatter works fine: enter image description here

How can I create the curve using plot?

CodePudding user response:

You can plot a smooth line curve by first determining the spline curve’s coefficients using the scipy.interpolate.make_interp_spline():

import numpy as np
import numpy as np
from scipy.interpolate import make_interp_spline
import matplotlib.pyplot as plt
 
# Dataset
x = np.array([1, 2, 3, 4, 5, 6, 7, 8])
y = np.array([20, 30, 5, 12, 39, 48, 50, 3])
 
X_Y_Spline = make_interp_spline(x, y)
 
# Returns evenly spaced numbers
# over a specified interval.
X_ = np.linspace(x.min(), x.max(), 500)
Y_ = X_Y_Spline(X_)
 
# Plotting the Graph
plt.plot(X_, Y_)
plt.title("Plot Smooth Curve Using the scipy.interpolate.make_interp_spline() Class")
plt.xlabel("X")
plt.ylabel("Y")
plt.show()

Result:

enter image description here

CodePudding user response:

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()

CodePudding user response:

It seems, that you have unsorted values in X_train. For instance, if

In  [1]: X_train
Out [1]: array([30, 20, 50, 40])

then

In  [2]: model.predict_proba(X_train)
Out [2]: array([0.2, 0.1, 0.8, 0.5])

Here, plt.plot will try to plot lines from point [30, 0.2] to point [20, 0.1], then from [20, 0.1] to [50, 0.8], then from [50, 0.8] to [40, 0.5].

Thus, the solution to your problem is to sort X_train before plotting =)

import numpy as np
X_train_sorted = np.sort(X_train)
y_train_sorted = model.predict_proba(X_train_sorted)
plt.scatter(X_train_sorted, y_train_sorted)
plt.plot(X_train_sorted, y_train_sorted)
  • Related