我目前正在使用 PyTorch 处理 CIFAR-10 数据集。我的目标是计算指定目标但具有特定特征子集的梯度。
例如,我的数据集中的图像为 32x32,有 3 个通道,总共 1024 个特征。我的目标是仅从左下角的 5x5 像素正方形中提取渐变。
通常,人们可以采用如下方法来使用所有可用的特征来获取梯度:
[...]
image, label = next(dataiter)
scores = model(image) #some pytorch model trained on cifar10
foo = loss(scores, target) #some loss function, eg. CrossEntropyLoss
foo.backward()
gradient = image.grad.clone()
[...]
目标是通过使用梯度仅修改 32x32 图像的一部分来提高准确性。
为此,您需要根据输入而不是模型权重计算梯度。
image, label = next(dataiter)
image.requires_grad_(True) # assuming image here is a tensor
# remove grad from weights
# this is not required but avoids unnecessary computation
for param in model.parameters():
param.requires_grad_(False)
scores = model(image)
foo = loss(scores, target)
foo.backward()
gradient = image.grad.clone() # gradient of image is now populated
要获取图像特定部分的梯度,您可以索引到图像梯度张量以抓取您想要的部分,或者屏蔽图像梯度张量中您不想要的部分。