使用Keras預測照片中的物體 (深度學習入門)

使用Keras預測照片中的物體 (深度學習入門)

26 影片觀看·2024年9月27日

使用Keras預測照片中的物體
深度學習已經成為了電腦視覺領域的一個重要工具,尤其是在物體識別上。在這影片中,我們將介紹如何使用Keras,一個用於深度學習的Python程式庫,來預測照片中的物體。

NUM_CLASSES = 10
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
x_train = x_train.astype('float32') / 255.0
x_test = x_test.astype('float32') / 255.0
y_train = to_categorical(y_train, NUM_CLASSES)
y_test = to_categorical(y_test, NUM_CLASSES)
print(x_train[54, 12, 13, 1])
定義類別數(10個)。
從 Keras 的 CIFAR-10 數據集中加載訓練和測試數據。
將圖像數據標準化到 [0, 1] 範圍。
將標籤轉換為 one-hot 編碼。

input_layer = Input((32, 32, 3))
x = Flatten()(input_layer)
x = Dense(200, activation='relu')(x)
# x = Dense(150, activation='relu')(x)
output_layer = Dense(NUM_CLASSES, activation='softmax')(x)
model = Model(input_layer, output_layer)
model.summary()
定義輸入層,輸入尺寸為 32x32x3 的圖像。
將輸入展平為一維。
添加一個有 200 個單元的全連接層,激活函數為 ReLU。
添加一個輸出層,輸出為 NUM_CLASSES(10)個類別,激活函數為 softmax。
顯示模型結構摘要。

opt = Adam(lr=0.0005)
model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy'])
model.fit(x_train, y_train, batch_size=32, epochs=10, shuffle=True)
定義優化器為 Adam,學習率為 0.0005。
編譯模型,使用損失函數為 categorical_crossentropy,評估指標為 accuracy。
使用訓練數據進行模型訓練,批次大小為 32,訓練 10 個世代。

model.evaluate(x_test, y_test)
使用測試數據評估模型的性能。

CLASSES = np.array(['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'])
preds = model.predict(x_test)
preds_single = CLASSES[np.argmax(preds, axis=-1)]
actual_single = CLASSES[np.argmax(y_test, axis=-1)]
n_to_show = 10
indices = np.random.choice(range(len(x_test)), n_to_show)
fig = plt.figure(figsize=(15, 3))
fig.subplots_adjust(hspace=0.4, wspace=0.4)
for i, idx in enumerate(indices):
img = x_test[idx]
ax = fig.add_subplot(1, n_to_show, i+1)
ax.axis('off')
ax.text(0.5, -0.35, 'pred = ' + str(preds_single[idx]), fontsize=10, ha='center', transform=ax.transAxes)
ax.text(0.5, -0.7, 'act = ' + str(actual_single[idx]), fontsize=10, ha='center', transform=ax.transAxes)
ax.imshow(img)
定義類別名稱對應的數組。
使用模型對測試數據進行預測。
根據預測結果和實際標籤得到對應的類別名稱。
隨機選擇 10 個測試樣本,並顯示圖像、預測結果和實際標籤。

影片中【predict_image.py】的下載網址:github.com/deepmind-python/nltk
請手動複製 github.com/deepmind-python/nltk 至瀏覽器的網址列上,然後在鍵盤上按 Enter鍵。