简体   繁体   中英

plotting a logistic regression :ValueError: x and y must have same first dimension

When I run my code I get an error message:

ValueError: x and y must have same first dimension.

import numpy as np 
from matplotlib import pyplot as plt 
from sklearn.linear_model import LogisticRegression

x1 = np.array([0,0.6,1.2,1.5,1.8,2.5,3.3,3.9,4,4.9,5.1])
y1 = np.array([0,0,0,0,0,0,0,0,0,0,0])

x2 = np.array([3.2,3.8,4.5,5.2,5.8,6.4,6.7,7.1,7.6,8.1,8.5,9])
y2 = np.array([1,1,1,1,1,1,1,1,1,1,1])

X = np.array([[0],[0.6],[1.2],[1.5],[1.8],[2.5],[3.3],[3.9],[4],[4.9],[5.1],[3.2],[3.8],[4.5],[5.2],[5.8],[6.4],[6.7],[7.1],[7.6],[8.1],[8.5],[9]])

Y = np.array([0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1])

plt.plot(x1,y1,"ro",color="blue")
plt.plot(x2,y2,"ro",color="red")

plt.axis([-2,10,-0.5,2])

plt.show()

Full traceback

Traceback (most recent call last):
  File "ml2.py", line 16, in <module>
    plt.plot(x2,y2,"ro",color="red")
  File "/usr/lib/python2.7/dist-packages/matplotlib/pyplot.py", line 3154, in plot
    ret = ax.plot(*args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/matplotlib/__init__.py", line 1814, in inner
    return func(ax, *args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/matplotlib/axes/_axes.py", line 1424, in plot
    for line in self._get_lines(*args, **kwargs):
  File "/usr/lib/python2.7/dist-packages/matplotlib/axes/_base.py", line 386, in _grab_next_args
    for seg in self._plot_args(remaining, kwargs):
  File "/usr/lib/python2.7/dist-packages/matplotlib/axes/_base.py", line 364, in _plot_args
    x, y = self._xy_from_xy(x, y)
  File "/usr/lib/python2.7/dist-packages/matplotlib/axes/_base.py", line 223, in _xy_from_xy
    raise ValueError("x and y must have same first dimension")
ValueError: x and y must have same first dimension

When calling plot , the two first arguments x and y must lists or arrays of the same length.

Your x2 and y2 are not of the same length.

To avoid the issue in the future, there are better ways to create an array filled with only one value, for example:

x2 = np.array([3.2,3.8,4.5,5.2,5.8,6.4,6.7,7.1,7.6,8.1,8.5,9])
y2 = np.full_like(x2, 1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM