# 维度数错误引起模型输入错误：For primitive\[Conv2D\], the x shape size must be equal to 4, but got 3.

**1. 系统环境**

```
硬件环境(Ascend/GPU/CPU): GPU
软件环境: MindSpore 版本: 1.7.0
执行模式： 静态图(GRAPH)
Python 版本: 3.7.6
操作系统平台: linux
```

**2. 报错信息**

2.1 问题描述

将处理好的图像tensor向量输入到模型，由于tensor的维度数未和模型的输入设置匹配导致运行错误。

2.2 报错信息

```
ValueError: mindspore/core/utils/check_convert_utils.cc:397 CheckInteger] For primitive[Conv2D], the x shape size must be equal to 4, but got 3.
```

2.3 脚本代码

```
if __name__ == '__main__':
    inputs = AFR.load_data('opencv_photo/input/')
    targets = AFR.load_data('opencv_photo/target/')
    adversarial = AFR.Attack(inputs[0], targets[0])
```

```
class Attack(object):
    if (seed != None): np.random.seed(seed)
    self.MEAN = Tensor([0.485, 0.456, 0.406])
    self.STD = Tensor([0.229, 0.224, 0.225])
    self.LOSS = Tensor(0)
    self.imageize = ToPILImage()
    self.tensorize = ToTensor()
    self.normalize = P.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
    self.resnet = get_net()
    self.input_tensor = Tensor(self.normalize(self.tensorize(input_img)))
    self.target_tensor Tensor(self.normalize(self.tensorize(target_img)))
    self.input_emb = self.resnet(self.input_tensor)
```

**3. 根因分析**

![](figures/4-109.png)

看报错信息the x shape size must be equal to 4, but got 3. 意思是x形状的大小必须等于4，但得到了3。

![](figures/5-110.png)

调试发现self.input\_tensor的维度数为3，需要增加一维。

**4. 解决方案**

解决方案说明：对self.input\_tensor的维度数进行扩充，来匹配模型的输入。增加的一维就是batch数。利用mindspore.ops.ExpandDims\(\)来进行维度的扩充。

修改后代码：

```
class Attack(object):
    if (seed != None): np.random.seed(seed)
    self.MEAN = Tensor([0.485, 0.456, 0.406])
    self.STD = Tensor([0.229, 0.224, 0.225])
    self.LOSS = Tensor(0)
    self.expand_dims = mindspore.ops.ExpandDims()
    self.imageize = ToPILImage()
    self.tensorize = ToTensor()
    self.normalize = P.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
    self.resnet = get_net()
    self.input_tensor = Tensor(self.normalize(self.tensorize(input_img)))
    self.target_tensor Tensor(self.normalize(self.tensorize(target_img)))
    self.input_emb = self.resnet(self.expand_dims(self.input_tensor,0))
```

正常执行结self.input\_tensor可以输入到模型得到正确的输出结果。

