Views
No views yet
1from transformers import AutoTokenizer, AutoModel
2import torch
3
4# Load PhysBERT tokenizer and model
5tokenizer = AutoTokenizer.from_pretrained("thellert/physbert_cased")
6model = AutoModel.from_pretrained("thellert/physbert_cased")
7
8# Sample text to embed
9sample_text = "Electrons exhibit both particle and wave-like behavior."
10
11# Tokenize the input text and pass it through the model
12inputs = tokenizer(sample_text, return_tensors="pt")
13outputs = model(**inputs)
14
15# Extract the token embeddings
16token_embeddings = outputs.last_hidden_state
17# Drop CLS and SEP tokens, then take the mean for the sentence embedding
18token_embeddings = token_embeddings[:, 1:-1, :]
19sentence_embedding = token_embeddings.mean(dim=1)@article{10.1063/5.0238090,
author = {Hellert, Thorsten and Montenegro, João and Pollastro, Andrea},
title = "{PhysBERT: A text embedding model for physics scientific literature}",
journal = {APL Machine Learning},
volume = {2},
number = {4},
pages = {046105},
year = {2024},
month = {10},
issn = {2770-9019},
doi = {10.1063/5.0238090},
url = {https://doi.org/10.1063/5.0238090},
eprint = {https://pubs.aip.org/aip/aml/article-pdf/doi/10.1063/5.0238090/20227307/046105\_1\_5.0238090.pdf},
}