最近,我一直在关注一个教程,其中我想出了以下代码
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
是一个具有二进制值 0
、1
的向量,X_set
是一个包含两个值的数组列。
我特别不理解如何解释以下代码行
X_set[y_set == j, 0], X_set[y_set == j, 1]
最佳答案
这里发生了一些事情。现在,我将放弃循环,但我们知道 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。
关于python - X_set[y_set == j, 0] 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51613863/