1

The model runs fine but I want to plot the results and cant seem to get it working, any help? I believe I have to make the local variable global for accuracy, loss, val_accuracy, val_loss but Im not sure how to do this in this case. I really need help with this issue as it is causing a lot of stress haha

bin_labels = {1:'EOSINOPHIL',2:'LYMPHOCYTE',3:'MONOCYTE',4:'NEUTROPHIL'}

def CNN(imgs,img_labels,test_imgs,test_labels,stride):

    #Number of classes (2)
    num_classes = len(img_labels[0])

    #Size of image
    img_rows,img_cols=imgs.shape[1],imgs.shape[2]
    input_shape = (img_rows, img_cols, 3)

    #Creating the model
    model = Sequential()

    #First convolution layer
    model.add(Conv2D(32, kernel_size=(3, 3),
                     activation='relu',
                     input_shape=input_shape,
                     strides=stride))

    #First maxpooling layer
    model.add(MaxPooling2D(pool_size=(2, 2)))

    #Second convolution layer
    model.add(Conv2D(64, (3, 3), activation='relu'))

    #Second maxpooling layer
    model.add(MaxPooling2D(pool_size=(2, 2)))

    #Third convolution layer
    model.add(Conv2D(128, (3, 3), activation='relu'))

    #Third maxpooling layer
    model.add(MaxPooling2D(pool_size=(2, 2)))

    #Convert the matrix to a fully connected layer
    model.add(Flatten())

    #Dense function to convert FCL to 128 values
    model.add(Dense(128, activation='relu'))

    #Final dense layer on which softmax function is performed
    model.add(Dense(num_classes, activation='softmax'))

    #Model parameters
    model.compile(loss='categorical_crossentropy',
                  optimizer='adam',
                  metrics=['accuracy'])

    #Evaluate the model on the test data before training your model
    score = model.evaluate(test_imgs,test_labels, verbose=1)

    print('\nKeras CNN binary accuracy:', score[1],'\n')

    #The model details
    history = model.fit(imgs,img_labels,
                        shuffle = True, 
                        epochs=3, 
                        validation_data = (test_imgs, test_labels))

    #Evaluate the model on the test data after training your model
    score = model.evaluate(test_imgs,test_labels, verbose=1)
    print('\nKeras CNN binary accuracy:', score[1],'\n')

    #Predict the labels from test data
    y_pred = model.predict(test_imgs)
    Y_pred_classes = np.argmax(y_pred,axis=1) 
    Y_true = np.argmax(test_labels,axis=1)

    #Correct labels
    for i in range(len(Y_true)):
        if(Y_pred_classes[i] == Y_true[i]):
            print("The predicted class is : " , Y_pred_classes[i])
            print("The real class is : " , Y_true[i])
            break
        
    #The confusion matrix made from the real Y values and the predicted Y values
    confusion_mtx = [Y_true, Y_pred_classes]

    #Summary of the model
    model.summary()

    return model,confusion_mtx

model,conf_mat = CNN(X_train,y_trainHot,X_test,y_testHot,1);





def plot_accuracy_loss_chart(history):
    epochs = [i for i in range(10)]
    fig , ax = plt.subplots(1,2)
    train_acc = model.history.history['accuracy']
    train_loss = model.history.history['loss']
    val_acc = model.history.history['val_accuracy']
    val_loss = model.history.history['val_loss']
    fig.set_size_inches(20,10)
    ax[0].plot(epochs , train_acc , 'go-' , label = 'Training Accuracy')
    ax[0].plot(epochs , val_acc , 'ro-' , label = 'Validation Accuracy')
    ax[0].set_title('Training & Validation Accuracy')
    ax[0].legend()
    ax[0].set_xlabel("Epochs")
    ax[0].set_ylabel("Accuracy")

    ax[1].plot(epochs , train_loss , 'g-o' , label = 'Training Loss')
    ax[1].plot(epochs , val_loss , 'r-o' , label = 'Validation Loss')
    ax[1].set_title('Training & Validation Loss')
    ax[1].legend()
    ax[1].set_xlabel("Epochs")
    ax[1].set_ylabel("Training & Validation Loss")
    plt.show()
plot_accuracy_loss_chart(model.history)

This is the error that I am receiving

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-136-ef9e8c8a1775> in <module>
     21     ax[1].set_ylabel("Training & Validation Loss")
     22     plt.show()
---> 23 plot_accuracy_loss_chart(model.history)

<ipython-input-136-ef9e8c8a1775> in plot_accuracy_loss_chart(history)
      2     epochs = [i for i in range(10)]
      3     fig , ax = plt.subplots(1,2)
----> 4     train_acc = model.history.history['accuracy']
      5     train_loss = model.history.history['loss']
      6     val_acc = model.history.history['val_accuracy']

KeyError: 'accuracy'
  • Please fix the indentation in your code! There's a very simple fix here (you need to `return` the result of your function) but it's harder to point out where exactly to make it when we can't see where the function ends. – Samwise Mar 24 '21 at 14:23
  • done now, first post sorry –  Mar 24 '21 at 14:26
  • What if you just replace `model.history.history` with `history` in your `plot_accuracy_loss_chart` function? – Samwise Mar 24 '21 at 14:47
  • TypeError: 'History' object is not subscriptable –  Mar 24 '21 at 14:50
  • Okay, so I guess you want to replace just `model.history` with `history` (sorry, I don't know this API at all), but you'll have the same error; it'll just make the code less confusing in general if you use the `history` you passed in as `model.history` rather than directly using `model.history` from the outer scope. Are you sure those "accuracy" values etc live in `History.history`? Your code is already getting the model (you don't have to make it a global), but it sounds like those values just aren't in the place within the model that you're trying to get them from. – Samwise Mar 24 '21 at 14:52
  • when using model.history.history it returns KeyError: 'accuracy'. when using model.history it returns TypeError: 'History' object is not subscriptable. when using history it returns TypeError: 'History' object is not subscriptable. when using model it returns ypeError: 'Sequential' object is not subscriptable. –  Mar 24 '21 at 15:07
  • Yes, I don't think that data exists in that part of the model. Your code doesn't include the `import` line for the model so I can't look up the API you're using, but I'd recommend googling "plot results " and you'll probably find a useful code snippet. – Samwise Mar 24 '21 at 15:36

0 Answers0