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)
原文地址:https://www.cnblogs.com/HL-blog/p/9438856.html