【问题标题】:1D array gets mapped to 2D plot and 3D array mapped to 2D plot1D 数组映射到 2D 图,3D 数组映射到 2D 图
【发布时间】:2020-07-13 17:49:14
【问题描述】:

我正在将 PCA 和 SVM 应用于 Sci-Kit Learn 的 load_digits 数据集。

这是一段代码:

from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.preprocessing import scale
from sklearn.svm import SVC

X_digits, y_digits = load_digits(return_X_y=True)
data = scale(X_digits)
reduced_data = PCA(n_components=2).fit_transform(data)

clf = SVC(kernel='rbf', C=1e6)
clf.fit(reduced_data, y_digits)

在上面的代码中,reduced_data 是一个 2D numpy 数组,y_digits 是一个 1D numpy 数组。

但是,当我编写以下代码时,我得到了两条线的二维图:

plt.plot(y_digits,'o') 
plt.plot(reduced_data,y_digits,'o')

我们不应该在第一行得到一个错误吗(因为y_digits 是一维的,matplotlib 不能绘制一维

plots),以及第二行的 3D 图,因为有两个来自 reduced_data 的输入变量和一个

output 变量为y_digits?我对如何使用 matplotlib 和解释结果有点困惑

【问题讨论】:

    标签: python matplotlib multidimensional-array pca


    【解决方案1】:

    我不是专家,但我相信 y_digits 数组是用 reshape(-1,1) 重塑一维数组的等效形式,因此我相信 matplotlib 将 y 解释为值的位置数组。这就是为什么当您调用 y_digits.shape 时输出为 (1797,) 的原因,逗号表示值在列中。

    如果你想要一个 3D 绘图,你应该像这样称呼它:

     #### Code for 3D Graph
     y = y_digits
     x = reduced_data[:,0] ### first column of 2D array
     z = reduced_data[:,1]  ### second column of 2D array
    
     fig = plt.figure()
     ax = fig.add_subplot(111, projection='3d')
     ax.scatter(x,y,z)
     plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-03
      • 1970-01-01
      • 2016-09-12
      • 2020-08-22
      • 2011-02-15
      • 1970-01-01
      • 2015-08-21
      相关资源
      最近更新 更多