我正在用这个博客学习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分配给数据的?谢谢
它是布尔或"掩码"索引数组,请参阅文档了解更多
>>> 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
给了我们类似于(如果是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)