当我运行代码时,我会收到一个错误消息:
valueerror:x和y必须具有相同的第一维。
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()
完整的追溯
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
调用 plot
时,两个第一个参数x和y必须列出相同长度的或数组。
您的x2
和y2
的长度不相同。
为了避免将来的问题,有更好的方法可以创建一个仅填充一个值的数组,例如:
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)