python - 预计 dense_4 有 2 个维度,但得到了形状为 (1449, 480, 640, 1) 的数组
问题描述
我正在尝试设计一个卷积网络来使用 Keras 估计图像的深度。
我有形状为 (1449,480,640,3) 的 RGB 输入图像和形状为 (1449,480,640,1) 的灰度输出深度图,但最后当我想设计最终图层时,我卡住了. 使用密集层
我有这个错误“预计dense_4有2维,但得到了形状为(1449、480、640、1)的数组”
根据 doc Keras将输入数据输入到形状为 (batch_size, units) 的密集层二维数组,我们必须将从卷积层接收到的输出维度更改为二维数组。
在将我的 gt ndarray 从 4d 重塑为 2d 之后,它也不起作用 gt=gt.reshape(222566400,2) 它向我显示了这个错误“预期dense_4具有形状(4070,)但得到了形状为(2,)的数组"
我知道,每个 480*640 位置都有 4070 个密集神经元,我如何重塑输出数组以适应依赖于 num 的密集层。神经元?请注意,我有 2 个密集层一个接一个
我的代码:
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)
解决方案
我猜你的架构有一些问题。如果我理解得很好,你想要的输出应该是大小(1449,480,640,1)。
首先,你的最后一层激活是一个softmax,你的损失被设置为'binary_crossentropy',这真的没有意义。此外,您还有另一个 DENSE 层,在此之前有 sigmoid 激活。这有什么原因吗?为什么要将两个 DENSE 连接在一起?
回到您的问题,您拥有的这种架构并不能真正解决您的问题。你需要的是一个Autoenocoder -ish 结构。为此,我建议在您将卷积结果展平后,在 UPSAMPLE 中添加更多层,然后是 Conv 层,并以某种方式对其进行管理以达到 (1449,480,640,1) 的输出大小。既然你想要灰度(我想你的意思是每个像素应该是 0 或 1),我建议使用 sigmoid 进行最后一层激活,然后使用二元交叉熵进行损失
推荐阅读
- sockets - TCP 连接在 recv() 函数处失败
- automation - 通话后自动向客户发送 WhatsApp 消息
- c++ - 如何使用 openssl 正确读取 PEM 格式的 X509 可信 CA
- next.js - Next js commerce 警告:预期的服务器 HTML 将包含匹配项
- javascript - 在 Vue.js 中捆绑:bpmn.io
- javascript - 删除图像时烦人的滚动 - TinyMCE
- python - Beautifulsoup 错误地将微笑数据中的 @ 解释为 [email protected]。我怎样才能拥有基本字符串?
- python - 手动附加 Django UUIDField
- angular - 接口“HTMLIonIconElement”不能同时扩展类型“IonIc on”和“HTMLStencilElement”
- mongodb - 客户端证书验证和没有 MongoDB TLS 连接有什么区别?