预期density_4具有2个维度,但数组的形状为(1449、480、640、1)

时间:2019-12-09 19:40:44

标签: python tensorflow keras depth estimation

我正在尝试设计一个卷积网络,以使用Keras估计图像的深度。

我具有形状为(1449,480,640,3)的RGB输入图像,并具有形状为(1449,480,640,1)的灰度输出深度图 但是最后,当我要设计最终层时,我陷入了困境。使用密集层

我遇到了这个错误“预计density_4具有2维,但数组的形状为(1449、480、640、1)”

根据doc Keras,将输入数据输入到形状为(batch_size,单位)的密集层 2D数组 并且必须将从卷积层接收的输出的尺寸更改为2D数组。

在将我的gt ndarray从4d重塑为2d之后,它也不起作用 gt = gt.reshape(222566400,2) 它告诉我这个错误 “预期density_4的形状为(40,),但数组的形状为(2,)””

我了解到480 * 640个位置中有4070个密集神经元 我该如何修复输出数组以适合依赖于num的密集层。神经元? 请注意,我彼此之间有2个致密层

enter image description here

我的代码:

import numpy as np
import h5py  # For .mat files
# data path
path_to_depth ='/content/drive/My Drive/DataSet/nyu_depth_v2_labeled.mat'

# read mat file
f = h5py.File(path_to_depth,'r')


pred = np.zeros((1449,480,640,3))
gt = np.zeros((1449,480,640,1))   

for i in range(len(f['images'])):
  # read 0-th image. original format is [3 x 640 x 480], uint8
  img = f['images'][i]

  # reshape
  img_ = np.empty([480, 640, 3])
  img_[:,:,0] = img[0,:,:].T
  img_[:,:,1] = img[1,:,:].T
  img_[:,:,2] = img[2,:,:].T


  # read corresponding depth (aligned to the image, in-painted) of size [640 x 480], float64
  depth = f['depths'][i]

  depth_ = np.empty([480, 640])
  depth_[:,:] = depth[:,:].T


  pred[i,:,:,:] = img_ 
  #print(pred.shape)#(1449,480,640,3)

  gt[i,:,:,0] = depth_ 
  #print(gt.shape)#(1449, 480, 640, 1)

# dimensions of our images.
img_width, img_height = 480, 640


gt=gt.reshape(222566400,2)
gt = gt.astype('float32')

from keras.preprocessing.image import ImageDataGenerator #import library to preprocess the dataset
from keras.models import Sequential #import keras models libraries
from keras.layers import Conv2D, MaxPooling2D ,BatchNormalization#import layers libraries
from keras.layers import Activation, Dropout, Flatten, Dense #import layers libraries
from sklearn.metrics import classification_report, confusion_matrix #import validation functions
import tensorflow as tf

#Training
model = Sequential() #model type initialization

#conv1
model.add(Conv2D(96, (11, 11),padding='VALID', strides=4,input_shape=(img_width, img_height, 3))) #input layer
model.add(Activation('relu'))

model.add(BatchNormalization(axis=1))

#pool1 
model.add(MaxPooling2D(pool_size=(3, 3),padding='VALID')) #Pooling Layer: reduces the matrices

#conv2
model.add(Conv2D(256, (5, 5),padding='SAME')) #input layer
model.add(Activation('relu'))
model.add(BatchNormalization(axis=1)) 

#conv3
model.add(Conv2D(384, (3, 3),padding='SAME')) #input layer
model.add(Activation('relu'))

#conv4
model.add(Conv2D(384, (3, 3),padding='SAME',strides=2)) #input layer
model.add(Activation('relu'))

#conv5
model.add(Conv2D(256, (3, 3),padding='SAME')) #input layer
model.add(Activation('relu'))

#pool2
model.add(MaxPooling2D(pool_size=(3, 3),padding='VALID')) #Pooling Layer: reduces the matrices

model.add(Flatten()) #this layer converts the 3D Layers to 1D Layer
model.add(Dense(4096,activation='sigmoid')) #densly connected NN Layers

model.add(Dropout(0.5)) #layer to prevent from overfitting


model.add(Dense (4070,activation='softmax')) #densly connected NN Layers

#Model configuration for training
model.compile(loss='binary_crossentropy', #A loss function calculates the error in prediction
              optimizer='rmsprop',        #The optimizer updates the weight parameters to minimize the loss function
              metrics=['accuracy'])       #A metric function is similar to a loss function, except that the results from evaluating a metric are not used when training the model.

model.fit(pred,gt,batch_size=9,epochs=161,verbose=1, validation_split=0.1) 

1 个答案:

答案 0 :(得分:1)

我猜您的体系结构存在一些问题。如果我理解得很好,那么输出中所需的大小应该是(1449,480,640,1)。

首先,您的最后一层激活是softmax,而您的损失被设置为“ binary_crossentropy”,这实际上没有任何意义。此外,在此之前,您还有另一个DENSE层,且具有S型激活。有什么理由吗?为什么要将DENSE拖在一起?

回到您的问题,您拥有的这种体系结构并不能真正解决您的问题。您需要的是 Autoenocoder -ish结构。为此,我建议您将卷积的结果展平后,在UPSAMPLE后面再加上Conv层,再添加一些层,并对其进行管理,以达到输出大小(1449,480,640,1)。由于您希望它为灰度级(我想您是说每个像素应该为0或1),因此我建议对最终层激活使用Sigmoid,然后对损失使用二进制交叉熵