【问题标题】:Keras input_tensor shape for transfer learning用于迁移学习的 Keras input_tensor 形状
【发布时间】:2018-09-02 22:47:35
【问题描述】:

我正在运行一个 CNN,用于使用 Keras 对医学扫描进行分类,并使用 imagenet 和 InceptionV3 进行迁移学习。我正在使用一些大小为X_train = (624, 128, 128, 1)Y_train = (624, 2) 的练习数据构建模型。

我正在尝试使用以下代码调整 input_tensor 的大小以适合我的图像形状 (128 x 128 x 1)。

input_tensor = Input(shape=(128, 128, 1)) 
base_model = InceptionV3(input_tensor=input_tensor,weights='imagenet',include_top=False)

这样做我得到一个值错误:

ValueError: Dimension 0 in both shapes must be equal, but are 3 and 32. Shapes 
are [3,3,1,32] and [32,3,3,3]. for 'Assign_753' (op: 'Assign') with input 
shapes: [3,3,1,32], [32,3,3,3]

有没有办法让这个模型接受我的图片格式?

编辑: 对于它的价值,这里是生成训练数据的代码。

X = []
Y = []
for subj, subj_slice in slices.items():
    # X.extend([s[:, :, np.newaxis, np.newaxis] for s in slice])
    subj_slice_norm = [((imageArray - np.min(imageArray)) / np.ptp(imageArray)) for imageArray in subj_slice]
    X.extend([s[ :, :, np.newaxis] for s in subj_slice_norm])
    subj_status = labels_df['deadstatus.event'][labels_df['PatientID'] == subj]
    subj_status = np.asanyarray(subj_status)
    #print(subj_status)
    Y.extend([subj_status] * len(subj_slice))

X = np.stack(X, axis=0)
Y = to_categorical(np.stack(Y, axis=0))]

n_samp_train = int(X.shape[0]*0.8)
X_train, Y_train = X[:n_samp_train], Y[:n_samp_train]

编辑2: 我认为另一种选择是采用形状为(780, 128, 128, 1) 的 X,克隆 780 个图像中的每一个并附加两个作为虚拟对象。这可能吗?导致(780, 128, 128, 3)

【问题讨论】:

  • 来自Keras documentation:“[输入张量] 应该正好有 3 个输入通道,并且宽度和高度应该不小于 139”。因此,您需要先调整(或填充)输入图像的大小,然后将它们提供给模型。对于通道,您可以复制两次,但我不确定它是否会对准确性产生负面影响。
  • post 提供了一些解决方案,但我不确定它们是否也适用于医学图像。最后,您应该尝试看看结果。
  • 复制频道两次——我自己也是这么想的。说得通。有没有直接的方法可以做到这一点,也许是直接修改我的 X 变量。还是应该在收集要带入 IDE 的图像时提前完成?
  • 你可以在 numpy 中使用tilerepeatX = np.repeat(X, 3, axis=-1)X = np.tile(X, (1, 1, 1, 3))
  • 完美。这正是我所需要的。我不知道 np.repeat 非常感谢。

标签: python machine-learning keras


【解决方案1】:

我们可以使用现有的 keras 层将现有的图像形状转换为预训练模型的预期形状,而不是使用 numpy 来复制通道。由于在训练之前复制通道可能会消耗 3 倍的内存,但在运行时集成此处理将节省大量内存。

你可以这样继续。

第 1 步:创建一个 Keras 模型,将您的输入图像转换为可以作为 base_model 输入的形状,如下所示:

from keras.models import Model
from keras.layers import RepeatVector, Input, Reshape

inputs = Input(shape=(128, 128, 1))
reshaped1 = Reshape(target_shape=((128 * 128 * 1,)))(inputs)
repeated = RepeatVector(n=3)(reshaped1)
reshaped2 = Reshape(target_shape=(3, 128, 128))(repeated)
input_model = Model(inputs=inputs, outputs=reshaped2)

第二步:定义预训练模型InceptionV3如下:

base_model = InceptionV3(input_tensor=input_model.output, weights='imagenet', include_top=False)

第 3 步: 将两个模型组合如下:

combined_model = Model(inputs=input_model.input, outputs=base_model.output)

这种方法的优点是 keras 模型本身会在运行时处理图像处理问题,例如通道复制。因此,我们不需要自己用 numpy 复制图像通道,结果将节省内存。

【讨论】:

    猜你喜欢
    • 2019-11-15
    • 2020-05-13
    • 2021-10-14
    • 2020-10-24
    • 2020-10-04
    • 2019-12-25
    • 1970-01-01
    • 1970-01-01
    • 2021-05-04
    相关资源
    最近更新 更多