keras數據預處理

數據預處理

  • 在使用 TensorFlow 做爲後端的時候,在 Keras 中,CNN 的輸入是一個4維數組(也被稱做4維張量),它的各維度尺寸爲 (nb_samples, rows, columns, channels)。其中 nb_samples 表示圖像(或者樣本)的總數,rowscolumns, 和 channels 分別表示圖像的行數、列數和通道數。
  • 下方的 path_to_tensor 函數實現以下將彩色圖像的字符串型的文件路徑做爲輸入,返回一個4維張量,做爲 Keras CNN 輸入。由於咱們的輸入圖像是彩色圖像,所以它們具備三個通道( channels 爲 3)。
    1. 該函數首先讀取一張圖像,而後將其縮放爲 224×224 的圖像。
    2. 隨後,該圖像被調整爲具備4個維度的張量。
    3. 對於任一輸入圖像,最後返回的張量的維度是:(1, 224, 224, 3)
  • paths_to_tensor 函數將圖像路徑的字符串組成的 numpy 數組做爲輸入,並返回一個4維張量,各維度尺寸爲 (nb_samples, 224, 224, 3)。 在這裏,nb_samples是提供的圖像路徑的數據中的樣本數量或圖像數量。你也能夠將 nb_samples 理解爲數據集中3維張量的個數(每一個3維張量表示一個不一樣的圖像。
    from keras.preprocessing import image                  
    from tqdm import tqdm
    
    def path_to_tensor(img_path):
        # 用PIL加載RGB圖像爲PIL.Image.Image類型
        img = image.load_img(img_path, target_size=(224, 224))
        # 將PIL.Image.Image類型轉化爲格式爲(224, 224, 3)的3維張量
        x = image.img_to_array(img)
        # 將3維張量轉化爲格式爲(1, 224, 224, 3)的4維張量並返回
        return np.expand_dims(x, axis=0)
    
    
    #
    img_paths是個可迭代的量
    def paths_to_tensor(img_paths):
        list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
        return np.vstack(list_of_tensors)
相關文章
相關標籤/搜索