python - 用于迁移学习的 Keras input_tensor 形状
问题描述
我正在运行一个 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]
Edit2:我认为另一种选择是采用我的 X 形状(780, 128, 128, 1)
,克隆 780 个图像中的每一个,并将两个附加为虚拟对象。这可能吗?导致(780, 128, 128, 3)
.
解决方案
我们可以使用现有的 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 复制图像通道,结果将节省内存。
推荐阅读
- android - React Native:android 模拟器不会显示开发者菜单
- php - 用背景颜色填充 png 透明度
- c# - 从另一个 Nuget 包引用的 Nuget 包中复制内容文件
- search-engine - Google Cloud Vision API - 部分匹配图像
- angular - 贝宝登录按钮在快速结帐中不起作用
- python - 将 pandas 中的行相乘并添加到迭代中
- android - Unity3d,当我触摸 InputField 时,键盘不显示
- django - 从表单编辑数据 - Django
- excel - 检查网络文件时进程卡住
- asp.net - 用于 Raspberry Pi 的 ASP.NET Core 应用程序在 VS2017 中使用 Docker