【问题标题】:Scatter plot: getting ValueError (x and y must be the same size)散点图:获取 ValueError(x 和 y 必须相同大小)
【发布时间】:2021-07-15 02:14:04
【问题描述】:

我正在尝试为我的线性回归模型绘制散点图。这是我尝试过的代码,但它引发了ValueError: x and y must be the same size

plt.scatter(X_test, y_test,  color='gray')
plt.plot(X_test, y_pred, color='red', linewidth=2)
plt.show()

当我检查 X_test、y_test 和 y_pred 的形状时,形状如下:

X_test.shape
(355, 2)

y_test.shape
(355,)

y_pred.shape
(355,)

我做错了什么?

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    您的 X_test 的形状为 (355, 2) 而 y_test 的形状为 (355,),因此形状和大小不同。我猜你的模型输入是二维的,散点图需要两个一维数组来确定气泡的位置

    我能想到你可以做的两件事:

    1- 分别绘制两个输入与预测:

    为此,我们将输入展平并分别从第一个和第二个元素开始获取其他所有元素

    flat = X_test.flatten()
    first_input = flat[::2]
    second_input = flat[1::2]
    
    plt.scatter(first_input, y_pred,  color='gray')
    plt.plot(first_input, y_test, color='red', linewidth=2)
    plt.show()
    
    plt.scatter(second_input, y_pred,  color='gray')
    plt.plot(second_input, y_test, color='red', linewidth=2)
    plt.show()
    

    2- 绘制颜色的精度,轴是您需要为其创建颜色数组的输入

    precision = y_pred == y_test
    colors = ["blue" if x else "red" for x in precision]
    

    这样做是首先将预测的每个元素与测试中的元素进行比较(这可以通过它们是 numpy 数组来完成) 然后它只是创建一个列表,其中“红色”用于失败的预测,“蓝色”用于使用列表理解的正确预测 然后将其传递给 color 关键字:

    plt.scatter(first_input, second_input,  color=colors)
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2020-02-23
      • 2017-05-30
      • 2022-01-12
      • 2023-03-31
      • 2014-08-25
      • 2021-10-20
      • 2022-01-17
      • 1970-01-01
      • 2021-08-17
      相关资源
      最近更新 更多