GitHub学习笔记——DeepEmbeddingModel_ZSL-Pytorch

https://github.com/yanghairui/DeepEmbeddingModel_ZSL-Pytorch/blob/master/CUB_attribute.py

需求1: 语义到视觉映射 ⇒ 视觉到语义映射


问题1:Can’t call numpy() on Variable that requires grad. Use var.detach().numpy() instead

分析:
kNNClassify的输入要求是numpy类型的
x_pred[i, :]是GPU上的Tensor

Traceback (most recent call last):
File “feat2attr.py”, line 119, in
print(compute_accuracy(test_x, test_att, test_att2label, test_x2label))
File “feat2attr.py”, line 24, in compute_accuracy
outputLabel = kNN.kNNClassify(x_pred[i, :], test_att, test_id, 1)
File “/home/yhr/DeepEmbeddingModel_ZSL-Pytorch/kNN.py”, line 30, in kNNClassify
diff = tile(newInput, (numSamples, 1)) - dataSet # Subtract element-wise
File “/home/yhr/anaconda2/envs/pytorch1.0/lib/python3.5/site-packages/numpy/lib/shape_base.py”, line 1147, in tile
c = _nx.array(A, copy=False, subok=True, ndmin=d)
File “/home/yhr/anaconda2/envs/pytorch1.0/lib/python3.5/site-packages/torch/tensor.py”, line 458, in array
return self.numpy()
RuntimeError: Can’t call numpy() on Variable that requires grad. Use var.detach().numpy() instead.

解决方案:

x_pred[i, :].cpu().detach().numpy()
  1. cpu()将变量从GPU上转移到CPU上
  2. detach.numpy()将Tensor转成numpy

你可能感兴趣的:(coding)