视频输入问题
传统的图像网络的输入数据格式input_shape =(batch, h, w, c),但对于视频输入(batch, number_frames, h, w, c)。我们在keras建模的时候batch_size默认为input_shape[0],无法改变,同时keras.layers.Conv2d等层操作也是按照4维张量处理输入输入。
解决方案一:维度切片堆叠(不推荐)
在模型搭建的过程中,在number_frames维度进行堆叠,即在喂给keras.layers.Conv2d前将数据按number_frames维切片,输出后再进行堆叠。
for ii in range (input_shape[0]):
if ii==0:
coarse_out=coarse_model(videoclip_cropped[:,ii])
else:
coarse_out=concatenate([coarse_out,coarse_model(videoclip_cropped[:,ii])], axis=1)
问题:当number_frames较大时,需要使用for循环建模时长异常的增加,在模型训练的时候发现重复堆叠操作会占用GPU,出现内存不足的错误提示,进而无法进行正常训练。
解决方案二:reshape(推荐)
先了解数据在内存中的存储形式,以及维度的定义:
存储数据时,内存并不支持这个维度层级概念,只能以平铺方式按序写入内存,因此这种层级关系需要人为管理,也就是说,每个张量的存储顺序需要人为跟踪。为了方便表达,我们把张量shape 中相对靠左侧的维度叫做大维度,shape 中相对靠右侧的维度叫做小维度,比如[2,4,4,3]的张量中,图片数量维度与通道数量相比,图片数量叫做大维度,通道数叫做小维度。
我们以一个(2,2,224,224,3)的五维输入数据为例:
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import Input, Model
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input, decode_predictions
def prepocess(x):
x = tf.io.read_file(x)
x = tf.image.decode_jpeg(x, channels=3)
x = tf.image.resize(x, [224,224])
x =tf.expand_dims(x, 0) # 扩维
x = preprocess_input(x)
return x
img_cat = prepocess('cat.jpg')
img_cow = prepocess('cow.jpg')
img_dog = prepocess('dog.jpg')
img_pig = prepocess('pig.jpg')
batch1 = tf.expand_dims(tf.concat([img_cat, img_cow], axis=0), axis=0)
batch2 = tf.expand_dims(tf.concat([img_dog, img_pig], axis=0), axis=0)
imgs = tf.concat([batch1, batch2], axis=0)
在正式输入网络前使用tf.reshape(imgs, [-1, 224,224,3]),将数据前两维展平为(4,224,224,3)喂给网络
inputs = tf.reshape(imgs, [-1, 224,224,3])
model = keras.applications.MobileNetV2(weights='imagenet')
Predictions = model.predict(inputs)
print('Predicted:', decode_predictions(Predictions, top=1))
结果如下:
Predicted: [[(‘n02124075’, ‘Egyptian_cat’, 0.41475537)], [(‘n02403003’, ‘ox’, 0.6601001)], [(‘n02108089’, ‘boxer’, 0.9366902)], [(‘n02395406’, ‘hog’, 0.75869286)]]
保持了原有的数据顺序
存在的问题:
由于存在batchnumber_frames输入,GPU会配置对应的2D卷积网络,导致计算的时候等于同时进行了batchnumber_frames个batch,计算内存不足,batch量减少,解决的方案是先提取特征,存储在本地。
备注:
以上是我个人的尝试后觉得可行的方案,如果有其他方式比如,自定义layers输入格式的方式也希望各位给出示例,非常需要与各位大佬交流
294



被折叠的 条评论
为什么被折叠?



