最近我在跟一个教程时遇到了以下代码
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 npX_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
索引 的信息。一旦你把步骤分解开来,事情并不复杂,但我认为这是一种不必要复杂的方式来完成这个任务。
for
循环的目的是为了根据 y_set
值是否等于 0 或 1 来重复绘图,并使用不同的颜色。