【问题标题】:Building a general numpy array index dynamically动态构建通用 numpy 数组索引
【发布时间】:2023-03-09 10:25:01
【问题描述】:

基本背景

我正在编写一些代码来简化对具有不同数量特征的数据的 SVM 训练,并使用用户指定的“切片”可视化这些 SVM 的决策边界。如果我的数据集中有n 特征和m 样本,我会生成一个(n+1)-dimensional 网格网格,其中沿第一个索引的每个切片都是m x m x ... 维度n 的网格。然后我可以使用我的 SVM 对我的网格中的每个数据点进行分类。

接下来我要做的是在用户指定的任意两个维度上绘制这些结果的一部分。当数据只有两个特征时,我的代码可以绘制出我想要的内容,但是一旦添加第三个特征,我就会开始遇到索引问题。

问题陈述

假设我有一个三维矩阵predictions,我想在我的网格网格mesh 中与index0=0 和index1=1 关联的所有值以及训练数据上绘制这些预测在那些维度。我可以通过如下函数调用来做到这一点:

import matplotlib.pyplot as plt
plt.contourf(mesh[index0,:,:,0], mesh[index1,:,:,0], pred[:,:,0])
plt.scatter(samples[:,index0], samples[:,index1], c=labels)
plt.show()

我想知道如何动态构建索引数组,这样如果index0=0 和index1=1,我们得到上面的代码,但如果index0=1 和index1=2,我们会得到:

plt.contourf(mesh[index0,0,:,:], mesh[index1,0,:,:], pred[0,:,:])

如果index0=0 和index1=2,我们会得到:

plt.contourf(mesh[index0,:,0,:], mesh[index1,:,0,:], pred[:,0,:])

如何动态构建这些?对于我可能无法提前知道数据将具有多少特征的情况,是否有更好的方法来解决这个问题?

更多详情

我尝试过这样的事情:

mesh_indices0 = [0]*len(mesh.shape)
mesh_indices0[0] = index0
mesh_indices0[index0+1] = ':'    # syntax error: I cannot add this dynamically
mesh_indices0[index1+1] = ':'    # same problem

我还尝试使用 mesh_indices = [:]*len(mesh.shape) 从相反的方向进行操作,但这也是无效的语法。我想过尝试类似的方法:

mesh_indices[index0+1] = np.r_[:len(samples[:, 1])]

其中samples 是我的m x n 观察集。不过这对我来说似乎很笨拙,所以我认为必须有更好的方法。

【问题讨论】:

    标签: python arrays numpy scikit-learn


    【解决方案1】:

    我不确定我是否完全理解你想要做什么,但如果你想操作切片,你应该使用 python slice 对象:

    mesh[index0,0,:,:]
    

    相当于:

    mesh[index0,0,slice(0,mesh.shape[2]),slice(0,mesh.shape[3])]
    

    还请注意,您可以使用切片和索引的列表或元组进行索引:

    inds = (index0, 0, slice(0,mesh.shape[2]), slice(0,mesh.shape[3]))
    mesh[inds]
    

    将它们放在一起,您可以列出:-等效slice 对象,然后用您的具体索引替换适当的对象。或者,换一种方式:

    mesh_indices = [0]*len(mesh.shape)
    mesh_indices[0] = index0
    mesh_indices[index0+1] = slice(0, mesh.shape[index0+1])
    mesh_indices[index1+1] = slice(0, mesh.shape[index1+1])
    

    【讨论】:

    • 这似乎正是我想要的。非常感谢!
    猜你喜欢
    • 2020-01-12
    • 1970-01-01
    • 2018-05-02
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多