target[y == l] = label 如何在 pytorch 教程中标记 make_blobs 数据集?

how target[y == l] = label work is labeling make_blobs dataset in pytorch tutorial?

我正在通过这个博客学习 PyTorch:[PyTorch 神经网络简介] (https://medium.com/biaslyai/pytorch-introduction-to-neural-network-feedforward-neural-network-model-e7231cff47cb) 我发现这段代码令人困惑:

from sklearn.datasets import make_blobs
def blob_label(y, label, loc): # assign labels
    target = numpy.copy(y)
    for l in loc:
        target[y == l] = label
    return target
x_train, y_train = make_blobs(n_samples=40, n_features=2, cluster_std=1.5, shuffle=True)
x_train = torch.FloatTensor(x_train)
y_train = torch.FloatTensor(blob_label(y_train, 0, [0]))
y_train = torch.FloatTensor(blob_label(y_train, 1, [1,2,3]))
x_test, y_test = make_blobs(n_samples=10, n_features=2, cluster_std=1.5, shuffle=True)
x_test = torch.FloatTensor(x_test)
y_test = torch.FloatTensor(blob_label(y_test, 0, [0]))
y_test = torch.FloatTensor(blob_label(y_test, 1, [1,2,3]))

target[y == l] = label 到底是怎么在这里工作的? 这行代码如何将 1 和 0 分配给数据? 谢谢!

它是布尔值或“掩码”索引数组,请参阅 doc 了解更多信息

>>> y = torch.arange(9).reshape(3,3)
>>> y
tensor([[0, 1, 2],
        [3, 4, 5],
        [6, 7, 8]])
>>> target = np.copy(y)

所以,target[y == l] = label
y == l 给我们布尔数组,如 (if l = 0)

>>> y == 0
tensor([[ True, False, False],
        [False, False, False],
        [False, False, False]])

我们可以使用布尔数组访问和赋值 y == 0

>>> target[y == 0]
array([0], dtype=int64)

>>> target[y == 0] = 999
>>> target
array([[999,   1,   2],
       [  3,   4,   5],
       [  6,   7,   8]], dtype=int64)