ktrain icon indicating copy to clipboard operation
ktrain copied to clipboard

something is wrong with the recent ktrain version

Open evilying opened this issue 3 years ago • 9 comments

Hi Amaiya,

I recently used the multi-label classifier finetuned with bert and other models. But I found that the accuracy becomes low.

So I used transformers only to verify the accuracy, which is high and expected (the source code is attached). So I am thinking that is there anything wrong when you update the ktrain tokenizer or text files?

I am not able to share the training/test dataset, but could you verify? Thanks!

import tensorflow as tf
from transformers import TFDistilBertForSequenceClassification, \
    DistilBertConfig, DistilBertTokenizerFast

MODEL_NAME = 'distilbert-base-uncased'
MAX_LENGTH = 44  # We truncate anything after the 200-th word to speed up training
config = DistilBertConfig.from_pretrained(MODEL_NAME)

tokenizer = DistilBertTokenizerFast.from_pretrained(MODEL_NAME)


train_encodings = tokenizer(list(train_texts), truncation=True, padding=True, 
                            max_length=MAX_LENGTH, return_tensors="tf")
test_encodings = tokenizer(list(test_texts), truncation=True, padding=True, 
                           max_length=MAX_LENGTH, return_tensors="tf")

train_dataset = tf.data.Dataset.from_tensor_slices((dict(train_encodings), train_labels))
test_dataset = tf.data.Dataset.from_tensor_slices((dict(test_encodings), test_labels))`

`from tensorflow.keras.initializers import TruncatedNormal
from tensorflow.keras.layers import Input, Dropout, Dense
from tensorflow.keras.losses import BinaryCrossentropy
from tensorflow.keras.metrics import AUC
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam

transformer_model = TFDistilBertForSequenceClassification.from_pretrained(
    MODEL_NAME, output_hidden_states=False
)

bert = transformer_model.layers[0]

input_ids = Input(shape=(MAX_LENGTH,), name='input_ids', dtype='int32')
inputs = {'input_ids': input_ids}

bert_model = bert(inputs)[0][:, 0, :] 

dropout = Dropout(config.dropout, name='pooled_output')
pooled_output = dropout(bert_model, training=False)
output = Dense(
    units=train_labels.shape[1],
    kernel_initializer=TruncatedNormal(stddev=config.initializer_range), 
    activation="sigmoid",  # Choose a sigmoid for multi-label classification
    name='output'
)(pooled_output)

model = Model(inputs=inputs, outputs=output, name='BERT_MultiLabel')
model.summary()

def multi_label_accuracy(y_true: tf.Tensor, y_pred: tf.Tensor) -> tf.Tensor:
    
    y_pred = tf.math.round(y_pred)
    exact_matches = tf.math.reduce_all(y_pred == y_true, axis=1)
    exact_matches = tf.cast(exact_matches, tf.float32)
    return tf.math.reduce_mean(exact_matches)

loss = BinaryCrossentropy()
optimizer = Adam(5e-5)
metrics = [
    multi_label_accuracy,
    "binary_accuracy", 
    AUC(name="average_precision", curve="PR", multi_label=True)
]
 
model.compile(optimizer=optimizer, loss=loss, metrics=metrics)
training_history = model.fit(
    train_dataset.shuffle(8000).batch(16), epochs=2, batch_size=16, 
    validation_data=test_dataset.batch(16)
)
print()

evilying avatar Jun 13 '23 23:06 evilying

Can you please share the ktrain code that you're using that is giving lower accuracy?

amaiya avatar Jun 13 '23 23:06 amaiya

Can you please share the ktrain code that you're using that is giving lower accuracy?

import ktrain
from ktrain import text
import pandas as pd
import os
import tensorflow as tf
import numpy as np

os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]="0"

train_data = pd.read_csv('./data/train_text2avatar_v1.0.csv', delimiter=',')
test_data = pd.read_csv('./data/test_text2avatar_v1.0.csv', delimiter=',')

print(len(train_data), len(test_data))

label_fields = list(train_data.columns[1:5])
print(label_fields)

x_train, y_train = train_data.Descriptions.values, train_data[label_fields].values
x_test, y_test = test_data.Descriptions.values, test_data[label_fields].values

MODEL_NAME = 'bert-base-uncased'
t = text.Transformer(MODEL_NAME, maxlen=128, class_names=label_fields)
train = t.preprocess_train(x_train, y_train)
val = t.preprocess_test(x_test, y_test)

model = t.get_classifier()

learner = ktrain.get_learner(model, train_data=train, val_data=val, batch_size=32)
learner.fit_onecycle(2e-4, 5, 
                    callbacks=[tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=5, min_delta=0.0001)], 
                    checkpoint_folder='models/bert-en/checkpoints')

learner.validate(class_names=t.get_classes())

predictor = ktrain.get_predictor(learner.model, preproc=t)
predictor.save('models/bert-en-t2a-predictor-v1.0')

evilying avatar Jun 13 '23 23:06 evilying

It doesn't look like the current implementation of the validate method supports multilabel classification (this is mentioned in the docstring). So, it sounds like this issue may be purely with the validate and not related to the model training or preprocessing. If you manually compute the accuracy in the same way you did in your first code snippet, this may confirm this to be the case. For instance, in the multilabel problem covered in the Text Classification tutorial notebook, the metric is computed manually like this:

from sklearn.metrics import roc_auc_score
y_pred = learner.model.predict(x_test, verbose=0)
score = roc_auc_score(y_test, y_pred)
print("\n ROC-AUC score: %.6f \n" % (score))

The validate method needs to be updated to support multilabel classification (which should be straightforward as the classification_report function from scikit-learn supports multilabel classification).

amaiya avatar Jun 14 '23 00:06 amaiya

I used the same parameter of lr=5e-5, batch size=16.

  • The following is the Transformers only outputs:
500/500 [==============================] - 19s 31ms/step - loss: 0.0369 - multi_label_accuracy: 0.9770 - binary_accuracy: 0.9884 - average_precision: 0.9996 - val_loss: 0.0034 - val_multi_label_accuracy: 1.0000 - val_binary_accuracy: 1.0000 - val_average_precision: 1.0000
Epoch 2/2
500/500 [==============================] - 15s 29ms/step - loss: 0.0025 - multi_label_accuracy: 1.0000 - binary_accuracy: 1.0000 - average_precision: 1.0000 - val_loss: 0.0013 - val_multi_label_accuracy: 1.0000 - val_binary_accuracy: 1.0000 - val_average_precision: 1.0000
  • The following is the Ktrain gives:
preprocessing train...
language: en
train sequence lengths:
        mean : 26
        95percentile : 32
        99percentile : 33
Is Multi-Label? True                                                                                                                              
preprocessing test...
language: en
test sequence lengths:
        mean : 26
        95percentile : 31
        99percentile : 33
Epoch 1/1 :                                                                                                                                       

begin training using onecycle policy with max lr of 5e-05...
Epoch 1/2
500/500 [==============================] - 35s 53ms/step - loss: 0.1337 - accuracy: 0.5230 - val_loss: 0.0063 - val_accuracy: 0.3405
Epoch 2/2
500/500 [==============================] - 26s 51ms/step - loss: 0.0043 - accuracy: 0.5095 - val_loss: 0.0030 - val_accuracy: 0.3445

evilying avatar Jun 14 '23 00:06 evilying

do you mean even in learner.fit_onecycle(), the computation of accuracy is not expected?

evilying avatar Jun 14 '23 00:06 evilying

Yes, the two training runs above are using different metrics. The val_accuracy in the ktrain example is using accuracy not binary_accuracy (which is what you used in your transformers example). Due to a change TensorFlow made some time ago, the values for accuracy are now much lower than binary_accuracy for multilabel classification. This used to not be the case. You can change the metric displayed during the training run by using the metrics argument to get_classifier (default is accuracy not binary_accuracy):

    def get_classifier(self, fpath=None, multilabel=None, metrics=["accuracy"]):

amaiya avatar Jun 14 '23 00:06 amaiya

I will evaluate it tonight and let you know. thank you!

evilying avatar Jun 14 '23 01:06 evilying

The following fixes were made and will be pushed to develop branch and will be included in next release:

  1. Fix validate to support multilabel classification reports
  2. ~Display a warning in get_classifier that recommends binary_accuracy if it is a multilabel problem.~ In get_classifier, use binary_accuracy automatically if it is a multilabel problem. Fixed in 39dd6ea92ef85a7b11bd73db15298e2193557982.

This commit will close this issue, but feel free to respond to this issue with additional questions/issues.

amaiya avatar Jun 14 '23 01:06 amaiya

As of v0.37.2, binary_accuracy (instead of accuracy) will automatically be used as default metric for multilabel classification problems.

amaiya avatar Jun 14 '23 22:06 amaiya