【问题标题】:PdfPages in Matplotlib saves the same figure twiceMatplotlib 中的 PdfPages 两次保存相同的图形
【发布时间】:2017-07-16 22:49:41
【问题描述】:

in the matplotlib documentation 提供的以下代码创建了 Hinton 图:

def hinton(matrix, max_weight=None, ax=None):
    """Draw Hinton diagram for visualizing a weight matrix."""
    ax = ax if ax is not None else plt.gca()

    if not max_weight:
        max_weight = 2 ** np.ceil(np.log(np.abs(matrix).max()) / np.log(2))

    ax.patch.set_facecolor('gray')
    ax.set_aspect('equal', 'box')
    ax.xaxis.set_major_locator(pl.NullLocator())
    ax.yaxis.set_major_locator(pl.NullLocator())

    for (x, y), w in np.ndenumerate(matrix):
        color = 'white' if w > 0 else 'black'
        size = np.sqrt(np.abs(w) / max_weight)
        rect = pl.Rectangle([x - size / 2, y - size / 2], size, size,
                             facecolor=color, edgecolor=color)
        ax.add_patch(rect)

    ax.autoscale_view()
    ax.invert_yaxis()

我想创建两个 Hinton 图:一个用于在我的单层 MLP 中从输入到隐藏层的权重,另一个从隐藏层到输出层。我试过了(based on this jupyter notebook):

W = model_created.layers[0].kernel.get_value(borrow=True)
W = np.squeeze(W)
print("W shape : ", W.shape) # (153, 15)

W_out = model_created.layers[1].kernel.get_value(borrow=True)
W_out = np.squeeze(W_out)
print('W_out shape : ', W_out.shape) # (15, 8)

with PdfPages('hinton_again.pdf') as pdf:
    h1 = hinton(W)
    h2 = hinton(W_out)
    pdf.savefig()

我也试过(based on this answer):

h1 = hinton(W)
h2 = hinton(W_out)

pp = PdfPages('hinton_both.pdf')
pp.savefig(h1)
pp.savefig(h2)
pp.close()

无论如何,结果都是一样的:W 的 Hinton 图被绘制了两次。如何在同一个 pdf 中包含我的第一组权重的 Hinton 图和我的第二组权重的 Hinton 图(只要我能获得两个 Hinton 图,我也会满足于两个单独的 pdf)?

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    pdf.savefig() 命令保存当前图形。由于当前图形只有一个,因此会保存两次。为了获得两个数字,需要创建它们,例如通过plt.figure(1)plt.figure(2)

    with PdfPages('hinton_again.pdf') as pdf:
        plt.figure(1)
        h1 = hinton(W)
        pdf.savefig()
        plt.figure(2)
        h2 = hinton(W_out)
        pdf.savefig()
    

    当然有很多不同的方法来保存这两个地块,另一种可能是

    fig, ax = plt.subplots()
    hinton(W, ax=ax)
    
    fig2, ax2 = plt.subplots()
    hinton(W_out, ax=ax2)
    
    with PdfPages('hinton_again.pdf') as pdf:
       pdf.savefig(fig)
       pdf.savefig(fig2)
    

    【讨论】:

    • 太棒了!非常感谢你。我添加的唯一更改是使用 pl.figure(1) 和 pl.figure(2),因为我将 pylot 导入为 pl,而不是 plt
    • 虽然你当然可以import matplotlib.pyplot as xasepgoah 或任何你喜欢的东西,但我认为在提问和回答关于 SO 的问题时最好保持使用 plt 的 matplotlib 风格。另请注意,recommended way of showing your gratitude 将只是对您收到的问题的答案进行投票。
    猜你喜欢
    • 2020-06-17
    • 2014-07-16
    • 2013-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多