教你使用TensorFlow2判斷細(xì)胞圖像是否感染
在本教程中,我們將使用 TensorFlow (Keras API) 實現(xiàn)一個用于二進(jìn)制分類任務(wù)的深度學(xué)習(xí)模型,該任務(wù)包括將細(xì)胞的圖像標(biāo)記為感染或未感染瘧疾。
數(shù)據(jù)集來源:https://www.kaggle.com/iarunava/cell-images-for-detecting-malaria
數(shù)據(jù)集包含2個文件夾
- 感染::13780張圖片
- 未感染:13780張圖片
總共27558張圖片。
此數(shù)據(jù)集取自NIH官方網(wǎng)站:https://ceb.nlm.nih.gov/repositories/malaria-datasets/
環(huán)境:kaggle,天池實驗室或者gogole colab都可以。
導(dǎo)入相關(guān)模塊
- import cv2
- import tensorflow as tf
- from tensorflow.keras.models import Sequential
- from tensorflow.keras.layers import Dense, Conv2D, MaxPool2D, Flatten, Activation
- from sklearn.model_selection import train_test_split
- import numpy as np
- import matplotlib.pyplot as plt
- import glob
- import os
對于圖片數(shù)據(jù)存在形狀不一樣的情況,因此需要使用 OpenCV 進(jìn)行圖像預(yù)處理。
將圖片變成 numpy 數(shù)組(數(shù)字格式)的形式轉(zhuǎn)換為灰度,并將其調(diào)整為一個(70x70)形狀。
- img_dir="../input/cell-images-for-detecting-malaria/cell_images"
- img_size=70
- def load_img_data(path):
- # 打亂數(shù)據(jù)
- image_files = glob.glob(os.path.join(path, "Parasitized/*.png")) + \
- glob.glob(os.path.join(path, "Uninfected/*.png"))
- X, y = [], []
- for image_file in image_files:
- # 命名標(biāo)簽 0 for uninfected and 1 for infected
- label = 0 if "Uninfected" in image_file else 1
- # load the image in gray scale 變成灰度圖片
- img_arr = cv2.imread(image_file, cv2.IMREAD_GRAYSCALE)
- # resize the image to (70x70) 調(diào)整圖片大小
- img_resized = cv2.resize(img_arr, (img_size, img_size))
- X.append(img_resized)
- y.append(label)
- return X, y
- X, y = load_img_data(img_dir)
查看X的shape。
- print(X.shape)
X的shape為(27558, 70, 70, 1),27558表示圖片的數(shù)據(jù),70*70表示圖片的長和寬像素。
另外,為了幫助網(wǎng)絡(luò)更快收斂,我們應(yīng)該進(jìn)行數(shù)據(jù)歸一化。在sklearn 中有一些縮放方法,例如:
在這里我們將除以255,因為像素可以達(dá)到的最大值是255,這將導(dǎo)致應(yīng)用縮放后像素范圍在 0 和 1 之間。
- X, y = load_img_data(img_dir)
- # reshape to (n_samples, 70, 70, 1) (to fit the NN)
- X = np.array(X).reshape(-1, img_size, img_size, 1)
- #從[0,255]到[0,1]縮放像素 幫助神經(jīng)網(wǎng)絡(luò)更快地訓(xùn)練
- X = X / 255
- # shuffle & split the dataset
- X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, stratify=y)
- print("Total training samples:", X_train.shape)
- print("Total validation samples:", X_test.shape[0])
使用sklearn的train_test_split()方法將數(shù)據(jù)集劃分為訓(xùn)練集和測試集,我們使用總數(shù)據(jù)的 10% 稍后對其進(jìn)行驗證。
在建立的模型中,我們將添加 3 個卷積層,然后Flatten是由層組成的全連接Dense層。
- model = Sequential()
- model.add(Conv2D(64, (3, 3), input_shape=X_train.shape[1:]))
- model.add(Activation("relu"))
- model.add(MaxPool2D(pool_size=(2, 2)))
- model.add(Conv2D(64, (3, 3)))
- model.add(Activation("relu"))
- model.add(MaxPool2D(pool_size=(2, 2)))
- model.add(Conv2D(64, (3, 3)))
- model.add(Activation("relu"))
- model.add(MaxPool2D(pool_size=(2, 2)))
- model.add(Flatten())
- model.add(Dense(64))
- model.add(Activation("relu"))
- model.add(Dense(64))
- model.add(Activation("relu"))
- model.add(Dense(1))
- model.add(Activation("sigmoid"))
- model.compile(loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"])
- print(model.summary())
由于輸出是二進(jìn)制的(感染或未感染),我們使用Sigmoid 函數(shù)作為輸出層的激活函數(shù)。
- # train the model with 10 epochs, 64 batch size
- model.fit(X_train, np.array(y_train), batch_size=64, epochs=10, validation_split=0.2)
在訓(xùn)練數(shù)據(jù)集及其驗證拆分上實現(xiàn)了94%的準(zhǔn)確率。
現(xiàn)在使用evaluate() 來評估測試數(shù)據(jù)集上的模型
- loss, accuracy = model.evaluate(X_test, np.array(y_test), verbose=0)
- print(f"Testing on {len(X_test)} images, the results are\n Accuracy: {accuracy} | Loss: {loss}")
輸出如下
- Testing on 2756 images, the results are
- Accuracy: 0.9404934644699097 | Loss: 0.1666732281446457
該模型在測試數(shù)據(jù)中也表現(xiàn)OK,準(zhǔn)確率達(dá)到94%
最后,我們將通過保存我們的模型來結(jié)束所有這個過程。
- model.save("model.h5")
【編輯推薦】