Paddle InvalidArgumentError: The input of Op(Conv) should be a 4-D or 5-D Tensor. But received: input's dimension is 3, input's shape is [1, 150, 150]

vhmi4jdf  于 2021-11-29  发布在  Java
关注(0)|答案(3)|浏览(1952)

How I can switch dimension of input image data ?

There is my data:

img = fluid.layers.data(name='img', shape=[ 1, 150, 150], dtype='float32')
label = fluid.layers.data(name='label', shape=[1], dtype='int64')

Data format:

{'data': array([[0.07843137, 0.13333333, 0.18039216, ..., 0.30588235, 0.27843137,
        0.25882353],
       [0.07058824, 0.10588235, 0.16862745, ..., 0.29803922, 0.28235294,
        0.25882353],
       [0.0745098 , 0.10980392, 0.16470588, ..., 0.29803922, 0.2745098 ,
        0.25882353],
       ...,
       [0.        , 0.        , 0.        , ..., 0.        , 0.        ,
        0.        ],
       [0.        , 0.        , 0.        , ..., 0.        , 0.        ,
        0.        ],
       [0.        , 0.        , 0.        , ..., 0.        , 0.        ,
        0.        ]]), 'label': array([0])}

Uploading data:

data_path_test = '../data/data52182/chest_xray/test'
uploaded_test_data = xray_dataset.upload_data(data_path_test)

def train_test(train_test_program):
    acc_set = []
    for data in uploaded_test_data:
        acc_np = exe.run(program=train_test_program,
                                feed={'img': np.array([data['data']]), 'label': np.array([data['label']])},
                                fetch_list=["accuracy_0.tmp_0"])

Get this:

InvalidArgumentError: The input of Op(Conv) should be a 4-D or 5-D Tensor. But received: input's dimension is 3, input's shape is [1, 150, 150].
  [Hint: Expected in_dims.size() == 4 || in_dims.size() == 5 == true, but received in_dims.size() == 4 || in_dims.size() == 5:0 != true:1.] at (/paddle/paddle/fluid/operators/conv_op.cc:59)
  [operator < conv2d > error]

How can I reshape image [150x150] into 4-D tensor?

sg2wtvxw

sg2wtvxw2#

Conv2D接收[N, C, H, W]格式的数据,N是batch size,C对于图像来说一般是RGB三通道,H, W是图像的高度和宽度

2j4z5cfb

2j4z5cfb3#

@heavengate
我也出现了类似的问题,我的环境是AIStudio默认的paddle-2.0。在预测的时候报这个问题,请问是我的使用方式不对吗?

import warnings
warnings.filterwarnings('ignore')
import numpy as np
import pandas as pd
import paddle
import paddle.vision.transforms as T
import os
from PIL import Image
from paddle.static import InputSpec

# 读取测试集数据

test_images = pd.read_csv('data/data74025/lemon/test_images.csv', usecols=['id'])
test_image_list = test_images['id'].values

# 构建数据预处理

test_transforms = T.Compose([
    T.Resize(size=(224, 224)),
    T.ToTensor(),
    # 归一化
    T.Normalize(
        mean=[0, 0, 0],    
        std=[255, 255, 255],
        to_rgb=True)
])

# 构建Dataset

class TestDataset(paddle.io.Dataset):
    """
步骤一:继承paddle.io.Dataset类
"""
    def __init__(self, image_list, image_dir=''):
        """
步骤二:实现构造函数,定义数据读取方式
"""
        super(TestDataset, self).__init__()
        self.images = []
        for img in image_list:
            self.images.append(os.path.join(image_dir, img))

    def load_img(self, image_path):
        image = Image.open(image_path)
        return image

    def __getitem__(self, index):
        """
步骤三:实现__getitem__方法,定义指定index时如何获取数据,并返回单条数据(训练数据,对应的标签)
"""
        image = self.load_img(self.images[index])
        img = data_transforms(image)
        return img

    def __len__(self):
        """
步骤四:实现__len__方法,返回数据集总数目
"""
        return len(self.images)

# test_loader

test_dataset = TestDataset(image_list=test_image_list, image_dir='data/data74025/lemon/test_images')
test_load = paddle.io.DataLoader(test_dataset, places=paddle.CPUPlace(), batch_size=64, num_workers=0)

# 加载模型

my_model = paddle.Model(LemonNet1())
my_model.load('work/model/destiny_cnn/destiny_cnn')
my_model.prepare()

# 预测

rstl = my_model.predict(test_load)
print(rstl)

错误信息

Predict begin...
---------------------------------------------------------------------------ValueError                                Traceback (most recent call last)<ipython-input-24-7adeb9cc014c> in <module>
     67 
     68 # 预测
---> 69 rstl = my_model.predict(test_load)
     70 print(rstl)
/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/paddle/hapi/model.py in predict(self, test_data, batch_size, num_workers, stack_outputs, callbacks)
   1701         outputs = []
   1702 
-> 1703         logs, outputs = self._run_one_epoch(test_loader, cbks, 'predict')
   1704 
   1705         outputs = list(zip(*outputs))
/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/paddle/hapi/model.py in _run_one_epoch(self, data_loader, callbacks, mode, logs)
   1818             else:
   1819                 if self._inputs is not None:
-> 1820                     outs = self.predict_batch(data[:len(self._inputs)])
   1821                 else:
   1822                     outs = self.predict_batch(data)
</opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/decorator.py:decorator-gen-348> in predict_batch(self, inputs)
/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/paddle/fluid/dygraph/base.py in _decorate_function(func, *args,**kwargs)
    313         def _decorate_function(func, *args,**kwargs):
    314             with self:
--> 315                 return func(*args,**kwargs)
    316 
    317         @decorator.decorator
/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/paddle/hapi/model.py in predict_batch(self, inputs)
   1036               print(out)
   1037         """
-> 1038         loss = self._adapter.predict_batch(inputs)
   1039         if fluid.in_dygraph_mode() and self._input_info is None:
   1040             self._update_inputs()
/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/paddle/hapi/model.py in predict_batch(self, inputs)
    727         inputs = [to_variable(x) for x in to_list(inputs)]
    728         self._input_info = _update_input_info(inputs)
--> 729         outputs = self.model.network.forward(*inputs)
    730         if self._nranks > 1 and isinstance(self.model._place, fluid.CUDAPlace):
    731             outputs = [_all_gather(o, self._nranks) for o in to_list(outputs)]
<ipython-input-7-a9e529675cb1> in forward(self, x)
     18 
     19     def forward(self, x):
---> 20         x = self.conv1(x)
     21         x = F.relu(x)
     22         x = self.pool1(x)
/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/paddle/fluid/dygraph/layers.py in __call__(self, *inputs,**kwargs)
    900                 self._built = True
    901 
--> 902             outputs = self.forward(*inputs,**kwargs)
    903 
    904             for forward_post_hook in self._forward_post_hooks.values():
/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/paddle/nn/layer/conv.py in forward(self, x)
    658             channel_dim=self._channel_dim,
    659             op_type=self._op_type,
--> 660             use_cudnn=self._use_cudnn)
    661         return out
    662 
/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/paddle/nn/functional/conv.py in _conv_nd(x, weight, bias, stride, padding, padding_algorithm, dilation, groups, data_format, channel_dim, op_type, use_cudnn, use_mkldnn, name)
    117                  "padding_algorithm", padding_algorithm, "data_format",
    118                  data_format)
--> 119         pre_bias = getattr(core.ops, op_type)(x, weight, *attrs)
    120         if bias is not None:
    121             out = nn.elementwise_add(pre_bias, bias, axis=channel_dim)
ValueError: (InvalidArgument) The input of Op(Conv) should be a 4-D or 5-D Tensor. But received: input's dimension is 3, input's shape is [64, 224, 224].
  [Hint: Expected in_dims.size() == 4 || in_dims.size() == 5 == true, but received in_dims.size() == 4 || in_dims.size() == 5:0 != true:1.] (at /paddle/paddle/fluid/operators/conv_op.cc:61)
  [operator < conv2d > error]

相关问题