簡體   English   中英

用於轉換和手動加載圖像的Keras input_shape

[英]Keras input_shape for conv2d and manually loaded images

我正在從多個384x286黑白圖像中手動創建數據集。

我加載這樣的圖像:

x = []
for f in files:
        img = Image.open(f)
        img.load()
        data = np.asarray(img, dtype="int32")
        x.append(data)
x = np.array(x)

這導致x是一個數組(num_samples,286、384)

print(x.shape) => (100, 286, 384)

閱讀keras文檔並檢查我的后端,我應該向卷積步驟提供一個由(rows,cols,channels)組成的input_shape

由於我不隨意知道樣本大小,因此我希望將其作為輸入大小傳遞,類似於

( None, 286, 384, 1 )

該模型的構建如下:

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape))
# other steps...

作為input_shape(286、384、1)傳遞會導致:

檢查輸入時出錯:預期conv2d_1_input具有4個維,但數組的形狀為(85,286,384)

傳遞as_input_shape(None,286,384,1)會導致:

輸入0與層conv2d_1不兼容:預期ndim = 4,找到的ndim = 5

我究竟做錯了什么 ? 我該如何重塑輸入數組?

input_shape設置為(286,384,1)。 現在,模型需要一個4維的輸入。 這意味着您必須使用.reshape(n_images, 286, 384, 1)重塑圖像。 現在,您添加了一個額外的維度,而無需更改數據,並且模型可以運行了。 基本上,您需要將數據調整為( n_imagesx_shapey_shapechannels )。

很棒的事情是您還可以使用RGB圖像作為輸入。 只需將channels更改為3。

還要檢查以下答案: Keras輸入說明:input_shape,units,batch_size,dim等

import numpy as np
from keras.models import Sequential
from keras.layers.convolutional import Convolution2D
from keras.layers.core import Flatten, Dense, Activation
from keras.utils import np_utils

#Create model
model = Sequential()
model.add(Convolution2D(32, kernel_size=(3, 3), activation='relu', input_shape=(286,384,1)))
model.add(Flatten())
model.add(Dense(2))
model.add(Activation('softmax'))

model.compile(loss='binary_crossentropy',
                  optimizer='adam',
                  metrics=['accuracy'])

#Create random data
n_images=100
data = np.random.randint(0,2,n_images*286*384)
labels = np.random.randint(0,2,n_images)
labels = np_utils.to_categorical(list(labels))

#add dimension to images
data = data.reshape(n_images,286,384,1)

#Fit model
model.fit(data, labels, verbose=1)

您的input_shape尺寸是正確的,即input_shape(286,384,1)

將輸入圖像重塑為4D [batch_size,img_height,img_width,number_of_channels]

input_image=input_image.reshape(85,286, 384,1)

model.fit(input_image,label)

我認為以下方法可以解決您的錯誤。

  1. 我們提供給第一個conv2d(順序模型的第一層)的input_shape應該類似於(286,384,1)或(寬度,高度,通道)。 其中batch_size不需要“無”維度。

  2. 您輸入的形狀可以是(batch_size,286,384,1)

這對您有幫助嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM