import tensorflow as tf
from transformers import TFAutoModel, AutoTokenizer
from datasets import load_dataset
model = TFAutoModel.from_pretrained("bert-base-uncased")
Downloading: 100%
570/570 [00:00<00:00, 22.2kB/s]
2023-01-21 14:49:15.558690: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:937] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2023-01-21 14:49:15.559793: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:937] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2023-01-21 14:49:15.560497: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:937] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2023-01-21 14:49:15.563043: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX2 AVX512F FMA
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2023-01-21 14:49:15.563369: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:937] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2023-01-21 14:49:15.564106: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:937] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2023-01-21 14:49:15.564755: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:937] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2023-01-21 14:49:20.386731: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:937] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2023-01-21 14:49:20.387657: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:937] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2023-01-21 14:49:20.388329: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:937] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2023-01-21 14:49:20.388921: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1510] Created device /job:localhost/replica:0/task:0/device:GPU:0 with 15043 MB memory: -> device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:00:04.0, compute capability: 6.0
Downloading: 100%
511M/511M [00:23<00:00, 23.4MB/s]
Some layers from the model checkpoint at bert-base-uncased were not used when initializing TFBertModel: ['mlm___cls', 'nsp___cls']
This IS expected if you are initializing TFBertModel from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).
Assistant
To perform inference using the BERTForClassification model after training, you will need to prepare input sentences in the same way as during training. Here's a step-by-step example, including tokenization and running the model for predictions on a new set of inputs.
User
How the model knows what are the labels and how many of them are?
Assistant
This IS NOT expected if you are initializing TFBertModel from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).
All the layers of TFBertModel were initialized from the model checkpoint at bert-base-uncased.
If your task is similar to the task the model of the checkpoint was trained on, you can already use TFBertModel for predictions without further training.
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
Downloading: 100%
28.0/28.0 [00:00<00:00, 1.10kB/s]
Downloading: 100%
226k/226k [00:00<00:00, 957kB/s]
Downloading: 100%
455k/455k [00:00<00:00, 919kB/s]
inputs = tokenizer(['Hello world', 'Hi how are you'], padding=True, truncation=True,
return_tensors='tf')
inputs
{'input_ids': <tf.Tensor: shape=(2, 6), dtype=int32, numpy=
array([[ 101, 7592, 2088, 102, 0, 0],
[ 101, 7632, 2129, 2024, 2017, 102]], dtype=int32)>, 'token_type_ids': <tf.Tensor: shape=(2, 6), dtype=int32, numpy=
array([[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]], dtype=int32)>, 'attention_mask': <tf.Tensor: shape=(2, 6), dtype=int32, numpy=
array([[1, 1, 1, 1, 0, 0],
[1, 1, 1, 1, 1, 1]], dtype=int32)>}
output = model(inputs)
output
TFBaseModelOutputWithPoolingAndCrossAttentions(last_hidden_state=<tf.Tensor: shape=(2, 6, 768), dtype=float32, numpy=
array([[[-0.16888332, 0.13606355, -0.13940018, ..., -0.6251125 ,
0.05217262, 0.36714536],
[-0.3632745 , 0.14121903, 0.8799885 , ..., 0.10433032,
0.2887578 , 0.37267894],
[-0.69859415, -0.69879794, 0.06450251, ..., -0.22103661,
0.00986893, -0.5939796 ],
[ 0.83098257, 0.12366717, -0.15119013, ..., 0.10309545,
-0.67792666, -0.26285172],
[-0.40266633, -0.01928236, 0.5732502 , ..., -0.20656842,
0.02338582, 0.20126349],
[-0.6228408 , -0.27453488, 0.1811763 , ..., -0.12944865,
-0.03839079, -0.05733156]],
def order(inp):
'''
This function will group all the inputs of BERT
into a single dictionary and then output it with
labels.
'''
data = list(inp.values())
return {
'input_ids': data[1],
'attention_mask': data[2],
'token_type_ids': data[3]
}, data[0]
converting train split of emotions_encoded to tensorflow format
Give me an example of inference and outpot of this moddel
Example of Inference
Prepare Input Text: Create a list of sentences that you want to classify.
Tokenize Input Text: Use the tokenizer to convert the text into the appropriate format expected by the BERT model.
Make Predictions: Pass the tokenized inputs to the model.
Interpret the Output: Convert the logits (raw model outputs) to predicted class labels.
Here’s how you can accomplish these steps in code:
python
import numpy as np
# Example sentences for inference
input_sentences = ["I am very happy today!", "This is a terrible experience."]
# Step 1: Tokenize the input
inputs = tokenizer(input_sentences, padding=True, truncation=True, return_tensors='tf')
# Step 2: Make predictions
logits = classifier(inputs)
# Step 3: Convert logits to probabilities
probabilities = tf.nn.softmax(logits)
# Step 4: Get predicted class labels
predictions = tf.argmax(probabilities, axis=1)
# Print the result
predicted_labels = predictions.numpy() # Convert tensor to numpy array for easy viewing
predicted_probabilities = probabilities.numpy() # Get the probabilities
# Display the results
for sentence, label, probability in zip(input_sentences, predicted_labels, predicted_probabilities):
print(f"Sentence: '{sentence}'")
print(f"Predicted Label: {label} (Probability: {probability})")
What the Output Could Look Like
Assuming you used a dataset of emotions where the labels are as follows:
0: joy
1: anger
2: fear
3: sadness
4: surprise
5: disgust
An example output from the above code might look like this:
code
Sentence: 'I am very happy today!'
Predicted Label: 0 (Probability: [0.85, 0.05, 0.02, 0.03, 0.03, 0.02])
Sentence: 'This is a terrible experience.'
Predicted Label: 1 (Probability: [0.01, 0.90, 0.01, 0.05, 0.03, 0.00])
In this output:
The predicted label is the index of the most probable class for each sentence.
The probability output indicates how confident the model is in its prediction (summing to 1 for each input).
This process allows you to easily classify new sentences based on the model you've trained!
In a typical machine learning workflow, especially when dealing with classification tasks like the one you're implementing with BERT, the model learns about the labels and how many there are during the training phase. Here’s how this works in more detail:
1. Label Definition in the Dataset
When you load your dataset using libraries such as datasets, the dataset contains a specified set of labels alongside the text data. In the case of the SetFit/emotion dataset you mentioned, it includes a set of labels with corresponding integers. For example, if you have:
0: joy
1: anger
2: fear
3: sadness
4: surprise
5: disgust
The dataset is structured to include these labels explicitly. When you preprocess the data, each text sample is paired with its respective label.
2. Model Configuration
During the initialization of your model (BERTForClassification in your case), you pass the number of classes (labels) you wish to classify into:
This informs the model that it should expect outputs corresponding to six different classes. The final classification layer (usually a dense layer with softmax activation) will output a vector of probabilities for each class.
3. Training Phase
While training the model, it sees many examples of text data paired with their respective labels. The model learns to map the text input to the corresponding output label through backpropagation, adjusting its weights based on the prediction errors over many training iterations. The model learns to recognize patterns associated with each label based on the examples provided.
4. Inference Phase
During inference, the model uses this learned information to make predictions based on new, unseen inputs. It doesn’t "know" the labels in a symbolic sense; instead, it identifies which output unit (associated with a class) has the highest predicted probability based on patterns learned during training.
Summary
Label Set: The labels and their corresponding integer mappings are predefined in the dataset. The model is informed of the available labels via the dataset during training.
Number of Classes: The number of classes is explicitly passed during model initialization, informing the structure of the output layer.
This configuration enables the model to classify new inputs effectively based on the training it underwent. The actual interpretation of the numeric output probabilities is done using the same label scheme established before training.