How do I get the embedding tensors from my fine-tuned BertForSequenceClassification
model? The issue is âBertForSequenceClassificationâ object has no attribute âembeddingsâ.
However, I can successfully get the BERT embedding for use in Tensorboardâs Embedding Projector tool with this code:
import transformers
from transformers import AutoTokenizer, AutoModelForSequenceClassification, AutoConfig
from torch.utils.tensorboard import SummaryWriter
import tensorflow as tf
import tensorboard as tb
# https://github.com/pytorch/pytorch/issues/30966#issuecomment-582747929
tf.io.gfile = tb.compat.tensorflow_stub.io.gfile
writer = SummaryWriter(log_dir='tensorboard_embedding_custom2')
model = transformers.BertModel.from_pretrained('bert-base-uncased')
tokenizer = transformers.BertTokenizer.from_pretrained('bert-base-uncased')
words = tokenizer.vocab.keys()
word_embedding = model.embeddings.word_embeddings.weight
writer.add_embedding(word_embedding,
metadata = words,
tag = f'word embedding')
writer.flush()
writer.close()