Search code examples
pythontensorflowtensorflow2.0z-indexsparse-matrix

InvalidArgumentError: indices[3] = [0,2917] is out of order. Many sparse ops require sorted indices


I'm facing the below error ::

InvalidArgumentError: indices[3] = [0,2917] is out of order. Many sparse ops require sorted indices. Use tf.sparse.reorder to create a correctly ordered copy. I'm not sure how to fix the error. I tried by reorder method which didn't work

Here is the code below ::

def score_transform(X):
    y_reshaped = np.reshape(X['rating'].values, (-1, 1))
    for index, val in enumerate(y_reshaped):
        if val >= 8:
            y_reshaped[index] = 1
        elif val >= 5:
            y_reshaped[index] = 2
        else:
            y_reshaped[index] = 0
    y_result = to_categorical(y_reshaped)
    return y_result
    

def convert_sparse_matrix_to_sparse_tensor(X):
    coo = X.tocoo()
    indices = np.mat([coo.row, coo.col]).transpose()
    return tf.sparse.reorder(tf.SparseTensor(indices, coo.data, coo.shape))


df_train = pd.read_csv("/content/drive/MyDrive/NLP_Prj/drugsComTrain_raw.csv", parse_dates=["date"])
df_test = pd.read_csv("/content/drive/MyDrive/NLP_Prj/drugsComTest_raw 2.csv", parse_dates=["date"])

df_train, df_test = train_test_split(df_all, test_size=0.33, random_state=42) 

X_train=(df_train['review_clean'].to_numpy())
X_test=(df_test['review_clean'].to_numpy())

test_train = np.concatenate([X_train, X_test])

X_onehot = vectorizer.fit_transform(test_train)
X_onehot1=convert_sparse_matrix_to_sparse_tensor(X_onehot)

#Model

model = keras.models.Sequential()

model.add(keras.layers.Dense(200, input_dim=len(vectorizer.get_feature_names())))
model.add(keras.layers.BatchNormalization())
model.add(keras.layers.Activation('relu'))
model.add(keras.layers.Dropout(0.5))

model.add(keras.layers.Dense(300))
model.add(keras.layers.BatchNormalization())
model.add(keras.layers.Activation('relu'))
model.add(keras.layers.Dropout(0.5))

model.add(keras.layers.Dense(256, activation='relu'))
model.add(keras.layers.Dense(3, activation='softmax'))


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


hist = model.fit(X_onehot1, y_train1, epochs=10, batch_size=128,verbose=1, validation_data=(X_onehot[157382:157482], y_train1[157382:157482]))

How to fix this issue ?


Solution

  • This error occurs mainly due to tensorflow and keras version mismatch. Don't do the import tensorflow directly such as

    import tensorflow as tf
    

    When I used below lines, the error was fixed. I can able to train the model. Instead use below lines of code:

    import tensorflow.python.keras.backend as K 
    sess = K.get_session()