簡體   English   中英

如何預測 Keras CNN model 中的單個圖像?

[英]How can I predict single image in Keras CNN model?

我正在按照本指南學習使用 CNN 進行圖像分類,並將此代碼實現到我的數據集中:

https://www.tensorflow.org/tutorials/images/classification

代碼更新

train_image_generator = ImageDataGenerator(rescale=1. / 255)  # Generator for our training data
validation_image_generator = ImageDataGenerator(rescale=1. / 255)  # Generator for our validation data

train_data_gen = train_image_generator.flow_from_directory(batch_size=batch_size,
                                                           directory=train_img_folder,
                                                           shuffle=True,
                                                           target_size=(IMG_HEIGHT, IMG_WIDTH),
                                                           class_mode='categorical',
                                                           color_mode='grayscale')

val_data_gen = validation_image_generator.flow_from_directory(batch_size=batch_size,
                                                              directory=valid_img_folder,
                                                              target_size=(IMG_HEIGHT, IMG_WIDTH),
                                                              class_mode='categorical',
                                                              color_mode='grayscale'
                                                              )

model = Sequential([
    Conv2D(16, 3, padding='same', activation='relu', input_shape=(IMG_HEIGHT, IMG_WIDTH, 1)),
    MaxPooling2D(),
    Conv2D(32, 3, padding='same', activation='relu'),
    MaxPooling2D(),
    Conv2D(64, 3, padding='same', activation='relu'),
    MaxPooling2D(),
    Flatten(),
    Dense(512, activation='relu'),
    Dense(3, activation='softmax')
])

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

history = model.fit_generator(
    train_data_gen,
    steps_per_epoch=total_train_value // batch_size,
    epochs=epochs,
    validation_data=val_data_gen,
    validation_steps=total_valid_value // batch_size
)

# Single prediction
img = []
temp = np.array(Image.open('path/to/pic.jpg').resize((256, 256), Image.ANTIALIAS))
temp.shape = temp.shape + (1,) # now its (256, 256, 1)
img.append(temp)
test = np.array(img) # (1, 1024, 1024, 1)
prediction = model.predict(test) 

當我嘗試 predict_generator function 時:

test_datagen = ImageDataGenerator(rescale=1 / 255.)

test_generator = test_datagen.flow_from_directory('test_images/',
                                                  classes=['0', '1', '2'],
                                                  color_mode='grayscale',
                                                  shuffle=True,
                                                  # use same size as in training
                                                  target_size=(256, 256))

preds = model.predict_generator(test_generator, steps=4) # I dont know what is steps doing. I put there because of error. 

我的第一個問題是:我可以獲得訓練和驗證的准確性,但我想獲得單張圖片的預測結果。 我怎樣才能做到這一點? 例子:

 foo = model.predict(path/to/pic.jpg) # foo returns 0-> 0.70 | 1-> 0.30

補充:當我嘗試使用 model.predict 時,我得到了這個錯誤:

 ValueError: Error when checking input: expected conv2d_1_input to have 4 dimensions, but got array with shape (1024, 1024)

或轉換為 2d(以及 3d)np.array 仍然相同。

我的第二個問題是:沒有完整的 %100 有什么方法可以預測? 我的意思是,如果我們有 2 個班級(貓和狗)並測試月球圖片,我想得到這樣的結果:

 %15 cat | %10 dog

不是

%50 cat | %50 dog

補充:我嘗試將垃圾 class 進行如下更改。 當我在history = model.fit_generator行上運行它時,出現以下錯誤:

 ValueError: Error when checking target: expected dense_2 to have shape (3,) but got array with shape (2,)


先感謝您

第一個問題:我可以得到訓練和驗證的准確性,但我想得到單張圖片的預測結果。 我怎樣才能做到這一點?

正如您在doc 中看到,您可以完全使用model.predict(x) ,只要您的x是:
- Numpy 數組(或類似數組),或數組列表(以防模型有多個輸入)。
- 如果模型具有命名輸入,則將輸入名稱映射到相應的數組/張量。
- 生成器或 keras.utils.Sequence 返回(輸入、目標)或(輸入、目標、樣本權重)。

您只需編寫讀取 .jpg 圖像並將其提供給模型的代碼。

第二個問題:有沒有辦法在沒有完整 %100 的情況下進行預測? 我的意思是如果我們有 2 個班級(貓和狗)並測試月球圖片,我想得到這樣的結果:

您可以創建第三類“垃圾”,為此您需要將網絡的最后一層更改為:

Dense(3, activation='softmax')

並將您的損失更改為categorical_crossentropy

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

並將class_mode更改為categorical而不是binary

在這種情況下,您將有狗:15%,貓:10%,垃圾:75%

編輯 conv2D 錯誤:

ValueError:檢查輸入時出錯:預期 conv2d_1_input 有 4 個維度,但得到了形狀為 (1024, 1024) 的數組

你有 :

Conv2D(16, 3, padding='same', activation='relu', input_shape=(IMG_HEIGHT, IMG_WIDTH, 3)),

這意味着,圖像(height, width, channel)
文檔中所見,由於這是 input_layer,因此您需要在 4D 中提供具有形狀的格式 : (samples, rows, cols, channels) 如果你只想給出一張圖像,你需要有一個形狀為(1, rows, cols, channels)的數組。

這可能會幫助您:

img.shape 是 (28,28,1)

我使用以下剪輯將其更改為(1,28,28,1)並且它有效!

img = np.expand_dims(img,0)
result = cnn.predict(img)

最后通過以下方式獲得您的 output:

result = result.round()

暫無
暫無

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

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