Skip to main content
 首页 » 编程设计

python之使用 Numpy 权重矩阵初始化 TensorFlow CNN 模型

2025年01月19日32me-sa

我正在努力将预训练的 matconvnet 模型手动转换为 tensorflow 模型。我使用 scipy.io 从 matconvnet 模型 mat 文件中提取了权重/偏差,并获得了权重和偏差的 numpy 矩阵。

代码片段,其中 data 是从 scipy.io 返回的字典:

for i in data['net2']['layers']: 
    if i.type == 'conv': 
        model.append({'weights': i.weights[0], 'bias': i.weights[1], 'stride': i.stride, 'padding': i.pad, 'momentum': i.momentum,'lr': i.learningRate,'weight_decay': i.weightDecay}) 

...

weights = { 
    'wc1': tf.Variable(model[0]['weights']),  
    'wc2': tf.Variable(model[2]['weights']), 
    'wc3': tf.Variable(model[4]['weights']), 
    'wc4': tf.Variable(model[6]['weights']) 
} 

...

例如,model[0]['weights'] 是从 matconvnet 模型中提取的 4x4x60 numpy 矩阵 for 层。这就是我为 9x9 输入定义占位符的方式。

X = tf.placeholder(tf.float32, [None, 9, 9]) #also tried with [None, 81] with a tf.reshape, [None, 9, 9, 1] 

当前问题:我无法获得匹配的排名。我一直得到 ValueError:

ValueError: Shape must be rank 4 but is rank 3 for 'Conv2D' (op: 'Conv2D') with input shapes: [?,9,9], [4,4,60]   

总结

  • 是否可以从 numpy 数组明确定义 tensorflow 模型的权重?
  • 为什么我的权重矩阵的秩是 4?我的 numpy 数组应该更像 [?, 4, 4, 60] 吗?我可以那样做吗?

尝试失败:

  • 旋转 numpy 矩阵:我知道 matlab 和 python 有不同的索引,(基于 0 的索引与基于 1 的索引,行主索引与列主索引)。尽管我相信我已经适本地转换了所有内容,但我仍然尝试使用像 np.rot90() 这样的库将 4x4x60 数组更改为 60x4x4。
  • 使用 tf.reshape:在用 tf.Variable 包装器包装权重后,我尝试在权重上使用 tf.reshape,但我得到 Variable has no attribute 'reshape'

注意: 请注意,我知道有许多脚本可以从 matconvnet 到 caffe,从 caffe 到 tensorflow(如此处所述,例如,https://github.com/vlfeat/matconvnet/issues/1021)。我的问题与 tensorflow 权重初始化选项有关:

请您参考如下方法:

我用 tf.reshape(...) 克服了这个障碍(而不是调用 weights['wc1'].reshape(...) )。我仍然不确定性能,或者这是否是一种非常幼稚的尝试。

更新 进一步测试,这种方法似乎至少在功能上是可行的(因为我已经创建了一个 TensorFlow CNN 模型,它将运行并产生与 MatConvNet 模型一致的预测。我不做任何声明关于两者之间的准确性)。

我正在分享我的代码。在我的例子中,这是一个非常小的网络——如果您试图将此代码用于您自己的 matconvnet 到 tensorflow 项目,您可能需要更多修改:https://github.com/melissadale/MatConv2TensorFlow