python - 使用 numpy ndarray 索引 numpy ndarray

标签 python numpy scikit-learn labeling

我正在制作有关 iris 数据集的教程。在这个过程中,我发现了一段代码,我无法理解:

它由两个 ndarray 组成:

iris.target_names 是一个带有目标变量标签的 numpy ndarray:

iris.target_names
>>> array(['setosa', 'versicolor', 'virginica'], dtype='<U10')

clf.predict(test[features]) 是一个 numpy ndarray,其中包含我的预测的编码数字:

clf.predict(test[features])
>>> array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1,
   1, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2],
  dtype=int64)

以下代码为我的预测创建一个带标签的 ndarray:

iris.target_names[clf.predict(test[features])]
>>> array(['setosa', 'setosa', 'setosa', 'setosa', 'setosa', 'setosa', 
'setosa', 'setosa', 'setosa', 'setosa', 'setosa', 'setosa', 'setosa', 
'setosa', 'setosa', 'versicolor', 'versicolor', 'versicolor', 'versicolor',  
'versicolor', 'versicolor', (...), dtype='<U10')

我思考了一段时间,但我不明白这是如何运作的。因为实际上我们用一个具有三个以上元素的一维数组来索引一个具有三个元素的一维数组,对吗?这怎么行?

如果有人可以帮助我提供有关此主题的一些提示,那就太好了。

谢谢,马库斯

最佳答案

如果我们忽略整个机器学习方面并将其提炼为一个简化的示例:

In[6]:
# our classes
classes=np.array(['a','b','c'])
# generate some random labels
predict= np.random.randint(0,3,10)
predict
Out[6]: array([0, 2, 1, 0, 2, 0, 1, 2, 1, 0])

现在,如果我们将 predict 数组作为 classes 的掩码传递,我们会将 0,1,2 转换为数组中的序号位置:

In[7]
classes[predict]
Out[7]: 
array(['a', 'c', 'b', 'a', 'c', 'a', 'b', 'c', 'b', 'a'], 
      dtype='<U1')

当您看到这个简单的示例时,并没有什么神奇的事情发生

您也可以在较小的数组上看到它:

In[8]:
classes[[1,0,2]]

Out[8]: 
array(['b', 'a', 'c'], 
      dtype='<U1')

因此,实际上预测的类别正在按位置索引回类别

传递数组的长度在这里无关紧要,您所做的只是向数组提供索引值,以便它创建一个包含该索引处的值的传递长度的新数组:

In[9]:
classes[[0,0,0,0]]

Out[9]: 
array(['a', 'a', 'a', 'a'], 
      dtype='<U1')

关于python - 使用 numpy ndarray 索引 numpy ndarray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50102719/

相关文章:

python - 删除 tkinter 文本默认绑定(bind)

python - 类型错误 : 'int' object is not callable in np. 随机种子

scikit-learn - 为什么我从 Scikit-learn API 与 XGBoost 的学习 API 得到不同的结果?

python - 查看 LabelEncoder 的映射

python - scikit-learn 在其树结构中的哪个位置保存每个叶节点的决策标签?

python - 将修改后的子框架嵌入到原始子框架中

python - tensorflow 中的 "y=x"和 y=tf.identity(x) 有什么区别

python - 如何在图像中找到形状的坐标

python - 在 python 中获取 1 到 100 万之间的随机数的最快方法

python - 在 Python 库中注册机器人框架监听器