Невозможно применить несколько одиночных изображений к большой сетке с помощью imshow - PullRequest
0 голосов
/ 09 сентября 2018

Итак, я следую вместе с книгой «Глубокое обучение на Python». Я пытаюсь воспроизвести результаты его кода, который помещает кучу этих изображений ниже (я могу успешно воспроизвести это изображение)

enter image description here

в большую решетку, вот так

enter image description here

Однако даже когда я копирую и вставляю его код (для большой сетки), я получаю

enter image description here

Ниже приведен код, который показывает мне изображение выше. Ниже этого кода будет вспомогательное использование кода в основном коде.

for layer_name in ['block3_conv1']:
    size = 64
    margin = 5

    # This a empty (black) image where we will store our results.
    results = np.zeros((8 * size + 7 * margin, 8 * size + 7 * margin, 3))

    for i in range(8):  # iterate over the rows of our results grid
        for j in range(8):  # iterate over the columns of our results grid
            # Generate the pattern for filter `i + (j * 8)` in `layer_name`
            filter_img = generate_pattern(layer_name, i + (j * 8), size=size)

            # Put the result in the square `(i, j)` of the results grid
            horizontal_start = i * size + i * margin
            horizontal_end = horizontal_start + size
            vertical_start = j * size + j * margin
            vertical_end = vertical_start + size
            results[horizontal_start: horizontal_end, vertical_start: vertical_end, :] = filter_img

    # Display the results grid
    plt.figure(figsize=(20, 20))
    plt.imshow(results)

def generate_pattern(layer_name, filter_index, size=150):
    # Build a loss function that maximizes the activation
    # of the nth filter of the layer considered.
    layer_output = model.get_layer(layer_name).output
    loss = K.mean(layer_output[:, :, :, filter_index])

    # Compute the gradient of the input picture wrt this loss
    grads = K.gradients(loss, model.input)[0]

    # Normalization trick: we normalize the gradient
    grads /= (K.sqrt(K.mean(K.square(grads))) + 1e-5)

    # This function returns the loss and grads given the input picture
    iterate = K.function([model.input], [loss, grads])

    # We start from a gray image with some noise
    input_img_data = np.random.random((1, size, size, 3)) * 20 + 128.

    # Run gradient ascent for 40 steps
    step = 1.
    for i in range(40):
        loss_value, grads_value = iterate([input_img_data])
        input_img_data += grads_value * step

    img = input_img_data[0]
    return deprocess_image(img)

def deprocess_image(x):
    x -= x.mean()
    x /= (x.std() + 1e-5)
    x *= 0.1

    x += 0.5
    x = np.clip(x,0,1)

    x *= 255
    x = np.clip(x,0,255).astype('uint8')

    return x 

1 Ответ

0 голосов
/ 11 сентября 2018

удалось обойти это (вы заметите, что изображения в сетках отличаются, потому что я копировал слой, отличный от того, что показывал мой код)

count = 0
n_rows = 8
n_columns = 8

f, axarr = plt.subplots(nrows=n_rows, ncols=n_columns, 
                        sharex=True, sharey=True,
                        figsize=(20,20))

for column in range(n_columns):

    for row in range(n_rows):
        axarr[row, column].imshow(generate_pattern('block3_conv1', count, size=150))
        f.subplots_adjust(hspace=0.01, wspace=0.01)
        count += 1

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...