X_set [y_set == j,0]是什么意思?

时间:2018-07-31 12:53:05

标签: python numpy machine-learning

最近,我一直在关注一个教程,其中提出了以下代码

for i, j in enumerate(np.unique(y_set)):
    plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],
        c = ListedColormap(('red', 'green'))(i), label = j)

此处,y_set是具有二进制值01X_set的向量,它是具有两列的数组。 我特别不理解如何解释以下代码行

X_set[y_set == j, 0], X_set[y_set == j, 1]

1 个答案:

答案 0 :(得分:4)

这里发生了一些事情。现在,我将删除循环,但我们知道j将采用y_set中的值,因此将为零或一。首先制作两个数组:

import numpy as np

X_set = np.arange(20).reshape(10, 2)
y_set = np.array([0, 1, 1, 1, 0, 0, 1, 1, 0, 1])

从上面开始,这段代码基本上是在做:

plt.scatter(filtered_values_in_first_column_of X_set, 
            filtered_values_in_second_column_of X_set)

y_set正在提供过滤器。我们可以通过建立步骤来实现:

print("Where y_set == 0: Boolean mask.")
print(y_set == 0)
print()

print("All rows of X_set indexed by the Boolean mask")
print(X_set[y_set == 0])
print()

print("2D indexing to get only the first column of the above")
print(X_set[y_set == 0, 0])
print()

您可以在numpy indexing上看到更多信息。一旦您分解步骤,它并不太复杂,但我认为这是完成此任务的不必要的复杂方法。

for循环的作用是,它们可以根据是否被y_set等于0或1的值进行过滤,以两种不同的颜色重复绘图。