TypeError:reshape:参数'input'位置1必须为Tensor,而不是numpy.ndarray

问题描述

我是一名高中生,在使用PyTorch和LIME方面没有太多经验。我的图像形状有很多麻烦。最初,我的图像形状为(3,224,224),但是LIME算法仅适用于这种形状的图像(...,...,3)。结果,我尝试更早地转置图像。这样做似乎使我取得了一些进步,但是现在我遇到了另一个错误。这是我的一些代码,以了解错误出现之前我一直在做什么。

def get_preprocess_transform():    
transf = transforms.Compose([
  #  transforms.ToPILImage(),#had to convert image to PIL as error was showing up two cells below about needing it in pil
    transforms.Resize(input_size),transforms.CenterCrop(input_size),transforms.ToTensor(),transforms.normalize([0.485,0.456,0.406],[0.229,0.224,0.225]),])    

return transf    

preprocess_transform = get_preprocess_transform() ## use your data_transform but in a method version
def batch_predict(image):
    model_ft.eval()
    batch = torch.reshape(image,(1,3,224))
    print(type(batch))
    
    
    
    logits = model_ft(batch)
    probs = F.softmax(logits,dim=1)
    return probs.detach().cpu().numpy()

print(img_t.shape)
img_t = torch.reshape(img_t,224))
test_pred = batch_predict(img_t)
test_pred.squeeze().argmax()
img_t = np.ones((3,224))
np.transpose(img_t,(2,1,0)).shape
img_x = np.transpose(img_t,0))
print(img_x.shape)
from lime import lime_image
explainer = lime_image.LimeImageExplainer()
explanation = explainer.explain_instance(img_x,## pass your image,do not transform
                                        batch_predict,# classification function
                                        top_labels=5,hide_color=0,num_samples=1000)

Here is the error message that comes from the "explainer cell"

解决方法

使用此命令将numpy.ndarray转换为张量

img = torch.from_numpy(img).float() #use appropriate name of variable

,

您正在通过NumPy数组而不是torch.reshape方法中的torch.tensor。因此最好在开始时将输入转换为torch.tensor

因此,img_t应该为torch.tensor,下面是一些实现方法

首先,使用torch.ones代替numpy np.ones

img_t = torch.ones((3,224,224))

或者稍后使用torch.from_numpynumpy.ndarray创建张量

img_t = np.ones((3,224))
img_t = torch.from_numpy(img_t)