Views
No views yet
pip install -U sentence-transformers1from sentence_transformers import SentenceTransformer, util
2
3sentences = ["Around 9 million people live in London.", "London is known for its financial district."]
4model = SentenceTransformer('kathaem/bert-base-cased-sentence-transformer-mnli-en')
5embeddings = model.encode(sentences)
6print(embeddings)1from transformers import AutoTokenizer, AutoModel
2import torch
3
4# Mean Pooling - Take attention mask into account for correct averaging
5def mean_pooling(model_output, attention_mask):
6 token_embeddings = model_output[0] #First element of model_output contains all token embeddings
7 input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
8 return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
9
10sentences = ["Around 9 million people live in London.", "London is known for its financial district."]
11
12# Load model from HuggingFace Hub
13tokenizer = AutoTokenizer.from_pretrained('kathaem/bert-base-cased-sentence-transformer-mnli-en')
14model = AutoModel.from_pretrained('kathaem/bert-base-cased-sentence-transformer-mnli-en')
15
16# Tokenize sentences
17encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')
18
19# Compute token embeddings
20with torch.no_grad():
21 model_output = model(**encoded_input)
22
23# Perform pooling to get sentence embeddings
24sentence_embeddings = mean_pooling(model_output, encoded_input['attention_mask'])
25print(sentence_embeddings)1@inproceedings{haemmerl-etal-2023-speaking,
2 title = "Speaking Multiple Languages Affects the Moral Bias of Language Models",
3 author = {H{\"a}mmerl, Katharina and
4 Deiseroth, Bjoern and
5 Schramowski, Patrick and
6 Libovick{\'y}, Jind{\v{r}}ich and
7 Rothkopf, Constantin and
8 Fraser, Alexander and
9 Kersting, Kristian},
10 editor = "Rogers, Anna and
11 Boyd-Graber, Jordan and
12 Okazaki, Naoaki",
13 booktitle = "Findings of the Association for Computational Linguistics: ACL 2023",
14 month = jul,
15 year = "2023",
16 address = "Toronto, Canada",
17 publisher = "Association for Computational Linguistics",
18 url = "https://aclanthology.org/2023.findings-acl.134/",
19 doi = "10.18653/v1/2023.findings-acl.134",
20 pages = "2137--2156",
21}