2017-07-26 27 views
2

我有一個NP陣列稱爲X_train具有以下屬性的使用Keras Conv2D層:如何使用可變形輸入

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)。但是,這給我的錯誤:

expected conv2d_1_input to have 4 dimensions, but got array with shape (139, 1)

我的猜測是,這個問題是輸入形狀(139,),而不是(139, None, None, 3)。但是我不確定如何轉換到那個。

+0

這就是問題所在,我想你會需要一個輸入/培訓目標在同一時間(批次大小爲1),否則您將無法創建具有一致尺寸的陣列 – gionni

+0

爲什麼不用零填充圖像以使它們都具有相似的尺寸? –

+0

@WilmarvanOmmeren好主意 - 有沒有這樣的功能? – megashigger

回答

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) 
+0

驚人的答案ty – megashigger