代码之家  ›  专栏  ›  技术社区  ›  Rocketq

用略读调整到更大的分辨率会导致路缘石中的形状类型错误

  •  1
  • Rocketq  · 技术社区  · 6 年前

    我的目标是在没有最后两个完全连接的层的情况下采用一个预先训练的模型,为cifar-10构建新的我自己的分类器。我面临的第一个问题是vgg至少希望 48*48*3 CIFAR-10数据集附带的张量 32*32*3 图像。我知道 ImageDataGenerator.flow_from_directory 内置 target_size 参数,但我不能在这里使用它,因为图像已经在内存中:

    from keras.applications import VGG16
    from keras.datasets import cifar10
    from keras.preprocessing.image import ImageDataGenerator
    import numpy as np
    (x_train, y_train), (x_test, y_test) = cifar10.load_data()
    vgg_conv = VGG16(weights='imagenet', include_top=False, input_shape=(48, 48, 3)) # 48 its a minimum width 
    
    >> type(x_train) #we have numpy here
    numpy.ndarray
    

    用于转换我正在使用的图像 skimage (不知道为什么,但似乎有效):

    from  skimage import transform
    new_shape = (48,88,3)
    x_train = np.asarray([transform.resize(image, new_shape) for image in x_train])
    

    接下来,我们将它传递给生成器,以便能够为nn提供批处理。不幸的是它没有 目标尺寸 参数,所以我用 resize 之前:

    train_generator = datagen.flow(
        x_train, 
        batch_size=batch_size, 
        shuffle=True)
    

    然后我在重复 train_generator 运气不好:

    for inputs_batch  in train_generator:
        features_batch = vgg_conv.predict(inputs_batch)
        train_features[i * batch_size : (i + 1) * batch_size] = features_batch 
        i += 1
        if i * batch_size >= nImages:
            break
    

    这是我得到的错误:

    值错误回溯(最近一次调用) --->2个功能部件批次=VGG转换预测(输入批次) 值错误:检查输入时出错:期望输入4具有形状(48、48、3),但得到的数组具有形状(48、88、3)

    这个问题可能与 flow generator ,其中:

        # Returns
            An `Iterator` yielding tuples of `(x, y)`
                where `x` is a numpy array of image data
                (in the case of a single image input) or a list
                of numpy arrays (in the case with
                additional inputs) and `y` is a numpy array
                of corresponding labels. If 'sample_weight' is not None,
            the yielded tuples are of the form `(x, y, sample_weight)`.
            If `y` is None, only the numpy array `x` is returned.
    

    所以我有两个问题:这里有什么问题,有没有更好的方法来调整图像的大小,也许有些内置于keras函数中?

    1 回复  |  直到 6 年前
        1
  •  1
  •   today    6 年前

    ( 注: as per requested by OP ,我已经将我的评论合并到这个答案中。)

    1. 你在这里输入错误: new_shape = (48,88,3) ;应该是 new_shape = (48,48,3) ,即 48 88 正如错误所说。

    2. 不要忘记通过传递来规范化图像 rescale=1./255 ImageDataGenerator 是的。

    3. 至于调整图像大小,您当前的方法是好的。但您也可以尝试中提供的解决方案 this SO answer .上述解决方案的优点是它将是模型的一部分,您可以为模型提供任意大小的图像。