Numpy Array of tensorflow.keras.preprocessing.text.Tokenizer.texts_to_sequences
is giving weird output for Training Labels as shown below:
(training_label_list[0:10]) = [list([1]) list([1]) list([1]) list([1]) list([1]) list([1]) list([1]) list([1]) list([1]) list([1])]
but is printing Normal Array for the Validation Labels,
(validation_label_list[0:10]) = [[16]
[16]
[16]
[16]
[16]
[16]
[16]
[16]
[16]
[16]]
In other words, type(training_label_list[0]) = <class 'list'>
but
type(validation_label_list[0]) = <class 'numpy.ndarray'>
Consequently, while Training the Model using Keras Model.fit
, it is resulting in the below Error,
ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type list).
This is the Link of the Google Colab, to reproduce the error easily.
Complete Code to reproduce the Error is given below:
!pip install tensorflow==2.1
# For Preprocessing the Text => To Tokenize the Text
from tensorflow.keras.preprocessing.text import Tokenizer
# If the Two Articles are of different length, pad_sequences will make the length equal
from tensorflow.keras.preprocessing.sequence import pad_sequences
# Package for performing Numerical Operations
import numpy as np
Unique_Labels_List = ['India', 'USA', 'Australia', 'Germany', 'Bhutan', 'Nepal', 'New Zealand', 'Israel', 'Canada', 'France', 'Ireland', 'Poland', 'Egypt', 'Greece', 'China', 'Spain', 'Mexico']
Train_Labels = Unique_Labels_List[0:14]
#print('Train Labels = {}'.format(Train_Labels))
Val_Labels = Unique_Labels_List[14:]
#print('Val_Labels = {}'.format(Val_Labels))
No_Of_Train_Items = [248, 200, 200, 218, 248, 248, 249, 247, 220, 200, 200, 211, 224, 209]
No_Val_Items = [212, 200, 219]
T_L = []
for Each_Label, Item in zip(Train_Labels, No_Of_Train_Items):
T_L.append([Each_Label] * Item)
T_L = [item for sublist in T_L for item in sublist]
V_L = []
for Each_Label, Item in zip(Val_Labels, No_Val_Items):
V_L.append([Each_Label] * Item)
V_L = [item for sublist in V_L for item in sublist]
len(T_L)
len(V_L)
label_tokenizer = Tokenizer()
label_tokenizer.fit_on_texts(Unique_Labels_List)
# Since it should be a Numpy Array, we should Convert the Sequences to Numpy Array, for both Training and
# Test Labels
training_label_list = np.array(label_tokenizer.texts_to_sequences(T_L))
validation_label_list = np.array(label_tokenizer.texts_to_sequences(V_L))
print('(training_label_list[0:10]) = {}'.format((training_label_list[0:10])))
print('(validation_label_list[0:10]) = {}'.format((validation_label_list[0:10])))
print('type(training_label_list[0]) = ', type(training_label_seq[0]))
print('type(validation_label_seq[0]) = ', type(validation_label_seq[0]))
I will be Grateful if someone can suggest me how can I get both Training Labels and Validation Labels in same Format, as I have spent so much time on it.