1

It looks like to the same problem with this tokenizer.texts_to_sequences Keras Tokenizer gives almost all zeros but it's not. I am working to create a text classification code but I'm facing a predicting problem in new stings using the tokenizer.

  1. Fit the tokenizer and use that tokenizer to convert the sentences (of a csv file->Pandas series) to sequences
tokenizer = Tokenizer()
tokenizer.fit_on_texts(X_train['clean_txt'])
X_train_seq = tokenizer.texts_to_sequences(X_train['clean_txt'])
X_test_seq = tokenizer.texts_to_sequences(X_test['clean_txt'])

#each sequence is the same length
pad_seq = 150
X_train_seq_padded = pad_sequences(X_train_seq, pad_seq)
X_test_seq_padded = pad_sequences(X_test_seq, pad_seq)
  1. Build And Evaluate a Sequential model
  2. I made some predicts and the result (unseen data from X_test) were right:
model.predict(X_test_seq_padded[52].reshape(1, pad_seq))
array([[2.5905947e-05]], dtype=float32)

Then I tried to have predictions in 2 different raw strings and I realized that I am getting the same result:

text = 'create a text classification code'
text = [text]
token_seq = tokenizer.texts_to_sequences(text)
token_seq_padded = pad_sequences(token_seq, pad_seq)
pred1 = model.predict(token_seq_padded)
pred1
array([[0.7042249]], dtype=float32)
token_seq
[[]]         <--- empty!!

I use a block of code that I found here (the link at the top) and have the same result with different string:

new_sample = ['Mathematics can describe many phenomena and concepts in music']
seq = tokenizer.texts_to_sequences(new_sample )
padded = pad_sequences(seq, maxlen=pad_seq)
pred = model.predict(padded)
pred
array([[0.7042249]], dtype=float32)
seq
[[]]         <--- empty!!

With my test data I have good results

precision    recall  f1-score   support

           0       0.98      0.99      0.98      1757
           1       0.97      0.95      0.96       809

    accuracy                           0.98      2566
   macro avg       0.98      0.97      0.97      2566
weighted avg       0.98      0.98      0.98      2566

What is that I can't see, leading me in wrong results? Tnx!!

  • I don't know Keras but could it be a problem due to different vocabulary, i.e. maybe the tokenizers cannot deal with words not seen during training? although 'a' 'and' 'in' are very frequent so it' probably not this. – Erwan Jun 21 '22 at 09:48
  • The data that I am using are mixed, half of them are Greek emails and the rest English emails. Nevertheless the Test data I'm using has the same shape and I get decent results. the problem I have is with raw strings as I mention earlier. Thank you!! – Konstantinos Kyritsis Jun 21 '22 at 16:18

0 Answers0