我使用Keras并以Tensorflow作为后端,以下是我的代码:
#图像加载和预处理
import os
from PIL import Image as Image
import numpy as np
#files是一个图像列表
files = [os.path.join('Save', file_i) for file_i in os.listdir('Save') if '.jpg' in file_i]
imgs = []
for image in files:
img = Image.open(image)
img = img.resize((227,227),Image.BILINEAR)
img = img.convert('L')
img = np.asarray(img)
array = img.astype('float32')
array /= 255
imgs.append(array)
imgs = np.asarray(imgs)
The_data = imgs.reshape(imgs.shape[0], 227, 227,1)
The_data = The_data.reshape(10, 25, 227, 227, 1)
from keras.models import Sequential
from keras.layers.convolutional import Convolution2D,Deconvolution2D
from keras.layers.convolutional_recurrent import ConvLSTM2D
from keras.layers.normalization import BatchNormalization
from keras.layers.wrappers import TimeDistributed
import numpy as np
import pylab as plt
model = Sequential()
#2个卷积层
model.add(TimeDistributed(Convolution2D(128, 11, 11 , border_mode='same', subsample = (4,4)), input_shape=(None,227, 227, 1)))
model.add(TimeDistributed(Convolution2D(64, 5, 5, border_mode='same', subsample = (2,2))))
model.add(TimeDistributed(ConvLSTM2D(nb_filter=64, nb_row=3, nb_col=3, border_mode='same', return_sequences=True)))
model.add(BatchNormalization())
model.add(TimeDistributed(ConvLSTM2D(nb_filter=32, nb_row=3, nb_col=3, border_mode='same', return_sequences=True)))
model.add(BatchNormalization())
model.add(TimeDistributed(ConvLSTM2D(nb_filter=64, nb_row=3, nb_col=3, border_mode='same', return_sequences=True)))
model.add(BatchNormalization())
model.add(TimeDistributed(Deconvolution2D(128, 5, 5,border_mode='same', output_shape=(None,57, 57, 128), subsample = (2,2))))
model.add(TimeDistributed(Deconvolution2D(1, 11, 11,border_mode='same', output_shape=(None,227, 227, 1), subsample = (4,4))))
model.compile(optimizer='adadelta', loss='binary_crossentropy')
model.fit(The_data,The_data, batch_size=5,nb_epoch=1)
model.summary()
我试图读取一些图像并对其进行预处理,然后应用(A)两个卷积层,(B)三个ConvLSTM层,以及(C)两个反卷积层。
我试图实现这个研究论文中使用的算法,但我发现每个layers(conv,deconv,convlstm)
都需要不同的处理,我已经搜索并知道convlstm
需要5维输入(帧数),但由于它不是模型中的第一层,如何更改其输入形状?
我有三个主要问题:
1- 卷积层抛出这个错误
检查模型目标时出错:期望convolution2d_2的形状为(None, 26, 26, 64)
但得到的数组形状
(250, 227, 227, 1)
2- 我已经注释了ConvLSTM2D因为它抛出这个错误
ValueError: 输入0与层convlstm2d_1不兼容:期望ndim=5,但找到ndim=4
我还注释了反卷积,因为我不知道output_shape
应该是什么。我知道最后应该重建输入图像。
3- 在model.fit
中,由于我在进行无监督学习,我没有标记数据,我应该保持这样还是怎样?
回答:
问题在于:
- 错误的
input_shape
– 数据应该裁剪成视频5-d
格式。这是通过reshape
和裁剪完成的。 - 向
conv
和deconv
层添加TimeDistributed
。 - 将
deconv
的输出形状更改为适当的值。 - 将
border_mode
更改为same
。
其他所有细节可能在问题的评论中找到。