[機器學習與深度學習] - No.6 ImageNet數據集預處理方式

在之前工作中,遇到了一個問題,在Google和Github的幫助下解決了,總結一下防止以後再次遇到。

問題描述: 當我們使用Keras自帶的VGG16,VGG19等模型在ImageNet上做圖像識別的時候 ,Top-1和Top-5的精度都會偏低一些,相對於Keras公佈出來的精度。例如,我自己測的VGG16的精度只有64%(Top-1),但是Keras上公佈的精度爲71.3%。後來在Google上調研了很久,發現是數據預處理的問題。

我使用的加載圖片的方式(部分代碼):

# loaded image path and label previously
image_list = []
from keras.preprocessing import image
for img_name in images_names:
    tmp_img = image.load_img(img_name, target_size=(224, 224))
    tmp_img = image.img_to_array(tmp_img)
    image_list.append(tmp_img)
image_arrays = np.array(image_list)
print(image_arrays.shape)

# prediction
x_validation=keras.applications.vgg16.preprocess_input(image_arrays)
vgg16_scores1 = vgg16_model.evaluate(x_validation,y_val_oc)
print(vgg16_scores1)

50000/50000 [==============================] - 158s 3ms/step
[1.5069317724227904, 0.64274]

這也是Keras官網中給的示例中的方法。可以看出,用這種方式讀取圖片,模型的精度只有64%。

後來我在Github 的這篇issue中找到了答案:如果想要獲得Keras官網中的精度,需要將ImageNet數據集按照如下方式進行預處理

  • Resize the shorter side of each image to 256 (將圖像的短邊長度調整爲256)
  • Resize the longer side to maintain the aspect ratio (調整長邊尺寸以保持長寬比)
  • Central 224x224 crop (從圖片中央截取 224x224的圖片)

此種方式的數據預處理代碼如下所示:

X_val = np.zeros((len(images_names), 224, 224, 3), dtype=np.float32)
# get_images
for i in range(len(images_names)):
    if i %2000 == 0:
        print("%d/%d" % (i, len(images_names)))
    
    # Load (as BGR)
    img = cv2.imread(images_names[i])
    
    # Resize
    height, width, _ = img.shape
    new_height = height * 256 // min(img.shape[:2])
    new_width = width * 256 // min(img.shape[:2])
    img = cv2.resize(img, (new_width, new_height), interpolation=cv2.INTER_CUBIC)
    
    # Crop
    height, width, _ = img.shape
    startx = width//2 - (224//2)
    starty = height//2 - (224//2)
    img = img[starty:starty+224,startx:startx+224]
    assert img.shape[0] == 224 and img.shape[1] == 224, (img.shape, height, width)
    
    # Save (as RGB)
    X_val[i,:,:,:] = img[:,:,::-1]
print(X_val[:10])

使用這種方式的模型精度如下所示:

50000/50000 [==============================] - 170s 3ms/step
[1.1673228887557983, 0.71268]

上面提到的issue中的完整的代碼鏈接在這裏

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章