ValueError: Data must be 1-dimensional

ValueError: Data must be 1-dimensional

当我尝试创建数据框来比较分类模型的实际(测试数据)和预测值时,出现错误。您可以在代码下方看到错误消息。代码的实现如下所示:

     df = pd.DataFrame({'Actual': y_test, 'Predicted': y_pred})
     df
     
     ValueError                                Traceback (most recent call last)
    <ipython-input-22-45d19b608f98> in <module>
---->  df = pd.DataFrame({'Actual': y_test, 'Predicted': y_pred})
     ValueError: Data must be 1-dimensional

编辑:y_test和y_pred的示例内容及其数据类型如下

     y_test
Out:array([[0],
   [0],
   [0],
   [0],
   [0],
   [1],
   [6],
   [0],
   [9],
   [0],
   [0],
   [5],
   [0],
   [6],
   [7],
   [0],
   [0],
   [9],
   [5],
   [0],
   [0],
   [0],
   [0],
   [5],
   [0],
   [3],
   [7],
   [0],
   [0],
   [9],
   [9],
   [0],
   [9],
   [7],
   [0],
   [0],
   [0],
   [0],
   [0],
   [9],
   [0],
   [8],
   [7],
   [9],
   [7],
   [5],
   [9],
   [0],
   [0],
   [0],
   [0],
   [0],
   [7],
   [0],
   [0],
   [0],
   [7],
   [3],
   [4],
   [5],
   [1],
   [8],
   [0],
   [9],
   [0],
   [0],
   [0],
   [0],
   [0],
   [8],
   [7],
   [0],
   [0],
   [0],
   [7],
   [5],
   [8],
   [7]])

  y_test.dtype
  Out:dtype('int32')

  y_pred
  Out:array([0, 7, 0, 3, 8, 0, 8, 7, 8, 0, 5, 7, 0, 0, 7, 0, 8, 0, 7, 0, 0, 
      0,3, 9, 0, 5, 0, 7, 9, 7, 0, 5, 5, 7, 0, 0, 0, 0, 9, 8, 7, 8, 1, 5,
   0, 0, 0, 0, 0, 0, 7, 0, 5, 0, 8, 9, 9, 0, 9, 0, 0, 9, 0, 9, 0, 3,
   0, 0, 9, 0, 0, 0, 0, 0, 0, 7, 0, 7])

  y_pred.dtype
  Out:dtype('int32')
  

我该如何解决这个问题?

y_test 是一个数组,里面有数组,所以不是一维向量。 使用 y_test.flatten 将其展平为一维数组:

df = pd.DataFrame({'Actual': y_test.flatten(), 'Predicted': y_pred})