jacobgil / keras-grad-cam

An implementation of Grad-CAM with keras
MIT License
656 stars 237 forks source link

value error when running grad-cam #8

Open kirk86 opened 7 years ago

kirk86 commented 7 years ago

Hi and thanks for this. I was wondering if you could give me a hint on why I receive the following error every time that I use the grad-cam.

Here is a traceback of the error:

Traceback (most recent call last):
  File "main.py", line 180, in <module>
    "conv2d_2")
  File "/Users/user/grad_cam.py", line 163, in run_gradcam
    layer_name)
  File "/Users/user/grad_cam.py", line 106, in grad_cam
    model.add(input_model)
  File "/Users/user/anaconda2/lib/python2.7/site-packages/keras/models.py", line 441, in add
    ' pre-existing inbound connections.')
ValueError: A layer added to a Sequential model must not already be connected somewhere else. Model received layer sequential_1 which has 4 pre-existing inbound connections.

Here is my model:


def cnn_model(img_rows=28, img_cols=28,
              channels=1, nb_filters=64, nb_classes=10):
    """
    :param img_rows: number of row in the image
    :param img_cols: number of columns in the image
    :param channels: number of color channels (e.g., 1 for MNIST)
    :param nb_filters: number of convolutional filters per layer
    :param nb_classes: the number of output classes
    :return:
    """

    # Define the layers successively
    if K.image_dim_ordering() == 'th':
        data_shape = (channels, img_rows, img_cols)
    else:
        data_shape = (img_rows, img_cols, channels)

    model = Sequential([
        Dropout(0.2, input_shape=data_shape),
        Convolution2D(nb_filters, 8, 8, subsample=(2, 2),
                      border_mode='same', activation='relu'),
        Convolution2D((nb_filters * 2), 6, 6, subsample=(2, 2),
                      border_mode='valid', activation='relu'),
        Convolution2D((nb_filters * 2), 5, 5, subsample=(1, 1),
                      border_mode='valid', activation='relu'),
        Dropout(0.5),
        Flatten(),
        Dense(nb_classes, activation='softmax')
    ])
    model.compile(optimizer='adam', loss='categorical_crossentropy',
                  metrics=['accuracy'])

    return model
ashiqimran commented 4 years ago

I also got the same error. Did you solve it?

kirk86 commented 4 years ago

I also got the same error. Did you solve it?

TBH, I don't remember what I did but I would suggest using updated versions of keras and python 3.6 at least.

Then I would create a simple model only with convolutional and dense layers. Avoid any dropout and batchnorm.

The other thing that I remember is that grad-cam operates only on tensors so make sure that your input to grad cam is the output of a conv layer from your model such that the output of that layer is a 3D or 4D tensor.

I hope these might help.