활연개랑

[tensorflow] Input 0 of layer "conv2d" is incompatible with the layer: expected min_ndim=4, found ndim=2. Full shape received: (300, 400) 본문

Python

[tensorflow] Input 0 of layer "conv2d" is incompatible with the layer: expected min_ndim=4, found ndim=2. Full shape received: (300, 400)

승해tmdhey 2022. 5. 4. 14:00
반응형

model inference 과정에서 다음과 같은 오류가 발생했습니다. 

ValueError: Exception encountered when calling layer "epvs_conv" (type EPVS_CONV).

Input 0 of layer "conv2d" is incompatible with the layer: expected min_ndim=4, found ndim=2. Full shape received: (300, 400)

Call arguments received:
  • inputs=tf.Tensor(shape=(300, 400), dtype=float32)

 

다음과 같은 오류가 발생한 이유는 shape이 맞지 않아서 입니다. 

제가 만든 모델에는 dimension이 4인 input (batchsize,width,height,channel) 이 들어가야 하는데, 제가 만든 데이터는 (width,height)로, dimension이 2밖에 되지 않기 때문에 오류가 나는 것입니다.

 

데이터의 channel이 1이라서 생략이 된다고 하더라도, input을 넣어줄 때에는 channel이 꼭 들어가져 있어야 하지만, 왜 오류가 나는지 알 수 없어서 헤매게 되었습니다.

 

일단 channel이 1인 경우 그 것을 데이터에 명시해주기 위하여 다음과 같은 코드를 사용합니다.

x = tf.expand_dims(x, axis =-1)

원래는 (300,400)이었던 shape이 (300,400,1)로 바뀌는 것을 보실 수 있습니다.

 

그리고 나서는 배치사이즈(데이터 개수)를 주어야 하는데, 저는 (tfrecord를 parsing하는 것이 아니라) 데이터를 직접 가공해서 inference를 하고 있었기 때문에 문제가 생겼었습니다.

 

그래서 해결한 방법으로는 그냥 낱개 데이터들을 list에 append시켜주는 방법입니다.

그리고 나서 tensor형태로 바꿔주게 되면 inference 할 때 predicted values가 한번에 나올 수 있게됩니다. 

아래 코드를 참고하시면 됩니다.

ary1 = tf.expand_dims(ary1, axis =-1)
ary2 = tf.expand_dims(ary2, axis =-1)

array=[ary1,ary2]
tensor = tf.convert_to_tensor(array)
pred_ary = model(tensor)

 

감사합니다. 오늘도 오류 없는 하루 되세요~