繁体   English   中英

如何使用具有可变形状输入的Keras Conv2D图层

[英]How to use Keras Conv2D layer with variably shaped input

我有一个名为X_train的NP数组,具有以下属性:

X_train.shape = (139,)
X_train[0].shape = (210, 224, 3)
X_train[1].shape = (220,180, 3)

换句话说,有139个观测值。 每个图像的宽度和高度都不同,但是它们都有3个通道。 因此,尺寸应为(139, None, None, 3) ,其中None =变量。

由于您未在图层中包括观察点数量的维度,因此对于Conv2D图层,我使用了input_shape=(None,None,3) 但这给了我错误:

预期conv2d_1_input具有4个维度,但数组的形状为(139,1)

我的猜测是,问题在于输入形状是(139,)而不是(139, None, None, 3) 我不确定如何转换为该。

解决您的问题的一种可能的方法是用零填充数组,以使它们的大小都相似。 然后,您的输入形状将类似于(139, max_x_dimension, max_y_dimension, 3)

以下功能将完成这项工作:

import numpy as np

def fillwithzeros(inputarray, outputshape):
    """
    Fills input array with dtype 'object' so that all arrays have the same shape as 'outputshape'
    inputarray: input numpy array
    outputshape: max dimensions in inputarray (obtained with the function 'findmaxshape')

    output: inputarray filled with zeros
    """
    length = len(inputarray)
    output = np.zeros((length,)+outputshape, dtype=np.uint8)
    for i in range(length):
        output[i][:inputarray[i].shape[0],:inputarray[i].shape[1],:] = inputarray[i]
    return output

def findmaxshape(inputarray):
    """
    Finds maximum x and y in an inputarray with dtype 'object' and 3 dimensions
    inputarray: input numpy array

    output: detected maximum shape
    """
    max_x, max_y, max_z = 0, 0, 0
    for array in inputarray:
        x, y, z = array.shape
        if x > max_x:
            max_x = x
        if y > max_y:
            max_y = y
        if z > max_z:
            max_z = z
    return(max_x, max_y, max_z)

#Create random data similar to your data
random_data1 = np.random.randint(0,255, 210*224*3).reshape((210, 224, 3))
random_data2 = np.random.randint(0,255, 220*180*3).reshape((220, 180, 3))
X_train = np.array([random_data1, random_data2])

#Convert X_train so that all images have the same shape
new_shape = findmaxshape(X_train)
new_X_train = fillwithzeros(X_train, new_shape)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM