使用SAM-LSTM-RESNET遇形状不匹配错误,求无改包解决方案
解决SAM-LSTM-RESNET权重加载的形状不匹配问题
问题描述
运行SAM-LSTM-RESNET的示例代码时触发形状不匹配错误,核心报错信息:
ValueError: The shape of the target variable and the shape of the target value in `variable.assign(value)` must match. variable.shape=(7, 7, 3, 64), Received: value.shape=(64, 3, 7, 7). Target variable: <KerasVariable shape=(7, 7, 3, 64), dtype=float32, path=conv1/kernel>
运行代码:
from sam_lstm import SalMap import os if not os.path.exists("\\samples"): os.makedirs("\\samples") SalMap.auto()
原因分析
错误源于维度顺序不兼容:
- 当前Keras/TensorFlow环境默认使用
channels_last格式(张量形状为(height, width, channels, filters)) - 包中加载的ResNet预训练权重是Theano格式的
channels_first(张量形状为(filters, channels, height, width))
不修改包代码的解决方案
方案1:全局设置Keras维度顺序为channels_first
在导入sam_lstm前,强制Keras使用channels_first格式,适配权重的维度:
import os # 设置环境变量指定数据格式 os.environ['IMAGE_DATA_FORMAT'] = 'channels_first' # 初始化Keras后端配置 from keras import backend as K K.set_image_data_format('channels_first') # 后续正常导入运行 from sam_lstm import SalMap if not os.path.exists("\\samples"): os.makedirs("\\samples") SalMap.auto()
方案2:一次性转换权重文件维度
如果不想全局修改维度配置,可手动转换预训练权重的维度,适配当前环境:
- 找到权重文件路径:默认在
~/.keras/weights/resnet50_weights_th_dim_ordering_th_kernels_notop.h5 - 运行以下代码转换权重维度:
import h5py # 替换为你的权重文件实际路径 weight_path = "~/.keras/weights/resnet50_weights_th_dim_ordering_th_kernels_notop.h5" with h5py.File(weight_path, 'r+') as f: for layer_key in list(f.keys()): if 'kernel' in layer_key: kernel_data = f[layer_key][:] # 将Theano格式(filters, channels, h, w)转为TensorFlow格式(h, w, channels, filters) converted_kernel = kernel_data.transpose(2, 3, 1, 0) # 删除原数据,写入转换后的数据 del f[layer_key] f.create_dataset(layer_key, data=converted_kernel)
转换完成后,直接运行原示例代码即可。
注意事项
- 方案1会全局修改Keras的图像数据格式,若同时使用其他依赖
channels_last的模型,可能引发新的兼容问题 - 方案2为一次性操作,转换后无需再修改代码,适合长期使用该包的场景
内容的提问来源于stack exchange,提问作者damian antonio gonzo
相关产品推荐
相关产品推荐

