After a model is built, how can I use it to predict the class of a single string?

model.predict() is returning something like [[0.41100174 0.5889983 ]] instead of it's predicted class (0 or 1).

Say I just built model like so:

hist = model.fit(data.x_train,
                 validation_data=(data.x_test, data.y_test),
                 callbacks=[checkpoint, estopping, tensorboard])

I'm looking to predict a string's class using model.predict(), but it returns something like [[0.41100174 0.5889983 ]] instead of it's predicted class (0 or 1).

The shape of data.x_test (used for validation data) is the same shape as data.x_data (reformatted string to predict): (1, 250, 70) (except the number of rows, obviously)

Here's how I'm trying to use the model to predict the class of a string.

def predict_string(model,s):
    df = pd.DataFrame([s], columns=['text'])
    df = df.reset_index(drop=True)
    df['label'] = [0]

    df.label = pd.to_numeric(df.label, errors='coerce') # Convert to integer
    df = df.dropna()
    df = df[df.label.apply(lambda x: x !="")]
    df = df[df.text.apply(lambda x: x !="")]

    vocab_len = 70
    data = char_preproc(df.text, df.label, vocab_len, True, None)
    y_pred = model.predict(data.x_data)
    return y_pred

s = "Best movie ever" # Out: [[0.41100174 0.5889983 ]]

# s = "Worst movie ever" # Out: [[0.5436389  0.45636114]]

y_pred = predict_string(model, s)
print("Review: {}\"\nPredict: {}".format(s, y_pred))

I'm not sure it matters, but for testing, I'm classifying movie reviews as good (1) or bad (0) using a Character-level CNN trained on the Rotten Tomatoes Movie Review dataset, running on GPU via Google Colab.

  • 1
    $\begingroup$ Those are the probabilities which your model thinks the given test image belongs to, you can use argmax(np.argmax()) $\endgroup$ – Aditya Oct 31 '18 at 6:05

[[0.41100174 0.5889983 ]] what this means is the probability of class 0 is 0.411 and probability of class 1 is 0.588. Since probability of class 1 is greater than probability of class 0, it belongs to class 1.

a = [[0.41100174 0.5889983 ]]


Output : 1

np.argmax will get you the class.

  • $\begingroup$ FYI: a = [[0.5 0.5 ]]; np.argmax(a) returns 1. Is there a numpy way to only return 1 if it's actually greater than the probability of the 0 class? $\endgroup$ – Ryan Nov 3 '18 at 0:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.