【问题标题】:How to use Keras Conv2D layer with variably shaped input如何使用具有可变形状输入的 Keras Conv2D 层
【发布时间】:2017-07-26 08:05:05
【问题描述】:

我有一个名为 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) 其中无 = 变量。

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

预计 conv2d_1_input 有 4 个维度,但得到的数组具有形状 (139, 1)

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

【问题讨论】:

  • 这就是问题所在,我认为您需要一次训练一个输入/目标(批量大小为 1),否则您将无法创建尺寸一致的数组
  • 为什么不用零填充图像,使它们都具有相似的大小?
  • @WilmarvanOmmeren 好主意 - 有这样做的功能吗?
  • 有,让我写下来
  • X_train 的形状怎么可能是(139, 1)X_train[0].shape = (210, 224, 3)

标签: python machine-learning tensorflow neural-network keras


【解决方案1】:

解决问题的一种可能方法是用零填充数组,以使它们都具有相似的大小。之后,您的输入形状将类似于(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)

【讨论】:

    猜你喜欢
    • 2019-01-24
    • 1970-01-01
    • 1970-01-01
    • 2020-04-29
    • 2018-08-15
    • 1970-01-01
    • 2018-02-27
    • 2017-05-25
    • 1970-01-01
    相关资源
    最近更新 更多