bert icon indicating copy to clipboard operation
bert copied to clipboard

Features extracted from layer -1 represent sentence embedding for a sentence?

Open mfxss opened this issue 8 years ago • 9 comments

Hi Jacob, Just to make sure, Do features extracted from layer -1 represent sentence embedding for a sentence ?
And if I want to extract the ssentence embedding for a sentence. Should I add sapce between Chinese character by myself in the input file? Thanks a lot !

mfxss avatar Nov 07 '18 03:11 mfxss

-1 means the last hidden layer. There are 12 or 24 hidden layers, so -1,-2,-3,-4 means 12,11,10,9 (for BERT-Base.) It's extracted for each token. There is not any "sentence embedding" in BERT (the hidden state of the first token is not a good sentence representation). If you want sentence representation that you don't want to train, your best bet would just to be to average all the final hidden layers of all of the tokens in the sentence (or second-to-last hidden layers, i.e., -2, would be better).

If you're using the latest version of the repo then you don't need to tokenize it yourself, the Chinese character tokenization is handled by tokenization.py.

jacobdevlin-google avatar Nov 07 '18 05:11 jacobdevlin-google

Hi, I wonder if you extract feature vectors with Chinese successfully. In my practice,it seems that the procedure can't recognize Chinese characters, and display UNK for a Chinese sentence.I don't know if it's a character encoding problem.

WalkerWen avatar Nov 07 '18 11:11 WalkerWen

Chinese wasn't supported until this weekend, please pull the latest version and then re-try.

jacobdevlin-google avatar Nov 07 '18 18:11 jacobdevlin-google

If you want sentence representation that you don't want to train, your best bet would just to be to average all the final hidden layers of all of the tokens in the sentence (or second-to-last hidden layers, i.e., -2, would be better).

Thanks Jacob. Curious as to why second to last hidden layer may be better?

ajbarber avatar Apr 03 '19 02:04 ajbarber

Hi @jacobdevlin-google, when you say "the hidden state of the first token is not a good sentence representation", is the "first token" here the CLS token? If so, I'm wondering why it's not a good sentence representation.

hlums avatar Apr 29 '19 17:04 hlums

I got the answer from https://bert-as-service.readthedocs.io/en/latest/section/faq.html#why-not-use-the-hidden-state-of-the-first-token-as-default-strategy-i-e-the-cls

hlums avatar Apr 29 '19 17:04 hlums

@ajbarber https://bert-as-service.readthedocs.io/en/latest/section/faq.html#why-not-the-last-hidden-layer-why-second-to-last

hlums avatar Apr 29 '19 17:04 hlums

thanks @hlums. My take on it is I believe the last layer is subject to the encoder-decoder attention mechanism, which produces this bias referred to in your link.

ajbarber avatar Apr 30 '19 00:04 ajbarber