After spending a lot of time, this is how I fixed it. I still don't know why but when the code is modified as follows, it works fine. I got the idea after seeing this solution for a similar but slightly different issue.
class_weights = compute_class_weight(
class_weight = "balanced",
classes = np.unique(train_classes),
y = train_classes
)
class_weights = dict(zip(np.unique(train_classes), class_weights))
class_weights