尝试使用 classification.ipny 可视化 caffe 中的所有层时出现轴不匹配数组错误

getting axes don't match array error when trying to visualize all layers in caffe using classification.ipny

我是 python 的新手并且对语言有非常基本的了解,话虽如此,我正在尝试获得所有层的权重及其 filters.For 的可视化这而不是重复:

# the parameters are a list of [weights, biases]
filters = net.params['conv1'][0].data
vis_square(filters.transpose(0, 2, 3, 1))

并更改图层名称,我尝试使用这样的循环:

 for layer_name, param in net.params.iteritems():
    # the parameters are a list of [weights, biases]
    filters = net.params[layer_name][0].data
    vis_square(filters.transpose(0, 2, 3, 1))

现在第一层工作正常,但出现此错误并停止 运行:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-16-cf7d5999a45c> in <module>()
      2     # the parameters are a list of [weights, biases]
      3     filters = net.params[layer_name][0].data
----> 4     vis_square(filters.transpose(0, 2, 3, 1))

ValueError: axes don't match array

这是vis_square()的定义(在caffe示例目录的classification.ipny中定义):

def vis_square(data):
    """Take an array of shape (n, height, width) or (n, height, width, 3)
       and visualize each (height, width) thing in a grid of size approx. sqrt(n) by sqrt(n)"""

    # normalize data for display
    data = (data - data.min()) / (data.max() - data.min())

    # force the number of filters to be square
    n = int(np.ceil(np.sqrt(data.shape[0])))
    padding = (((0, n ** 2 - data.shape[0]),
               (0, 1), (0, 1))                 # add some space between filters
               + ((0, 0),) * (data.ndim - 3))  # don't pad the last dimension (if there is one)
    data = np.pad(data, padding, mode='constant', constant_values=1)  # pad with ones (white)

    # tile the filters into an image
    data = data.reshape((n, n) + data.shape[1:]).transpose((0, 2, 1, 3) + tuple(range(4, data.ndim + 1)))
    data = data.reshape((n * data.shape[1], n * data.shape[3]) + data.shape[4:])

    plt.imshow(data); plt.axis('off')

这里有什么问题?
如果有人能帮我解决这个问题,我将不胜感激。

对于后续层,通道数 > 64。例如,如果第一层有 num_output: 64,第二层也有 num_output: 64,则 4D 矩阵的形状存储权重的是 64 x 64 x height x width。转置后,它是 64 x height x width x 64.

您的函数无法处理 64 层对象,尽管它非常适合 3 层对象。

我会 n = int(np.ceil(np.sqrt(data.shape[0] * data.shape[3]))) 并将整个对象重塑为 1 层对象。我不认为将卷积核可视化为 RGB 会给您任何见解。

对于遇到类似问题的任何人("axes don't match array" 错误):在转置之前,我将数据放入一个变量中,给出了确切的大小。如果我的数据是大小为10*12*15的数据:

DataI = Data [0:9, 0:11, 0:14]
DataII = np.transpose(DataI,(0,2,1))

这对我有用。