Views
No views yet
1from open_clip import create_model_from_pretrained, get_tokenizer
2import torch
3from urllib.request import urlopen
4from PIL import Image
5
6# import model, processor and tokenizer
7model, processor = create_model_from_pretrained('hf-hub:xcwangpsu/MedCSP_clip')
8tokenizer = get_tokenizer('hf-hub:xcwangpsu/MedCSP_clip')
9
10
11
12# encode image:
13
14# import raw radiological image:
15image = Image.open(urlopen("https://huggingface.co/xcwangpsu/MedCSP_clip/resolve/main/image_sample.jpg"))
16
17# preprocess the image, the final tensor should have 4 dimensions (B, C, H, W)
18processed_image = processor(image)
19processed_image = torch.unsqueeze(processed_image, 0)
20print("Input size:", processed_image.shape)
21
22# encode to a single embedding
23image_embedding = model.encode_image(processed_image)
24print("Individual image embedding size:",image_embedding.shape)
25
26# sequential encoding
27seq_image_embedding = model.visual.trunk.forward_features(processed_image)
28print("Sequential image embedding size:",seq_image_embedding.shape)
29
30
31# encode text:
32
33text = "Chest X-ray reveals increased lung opacity, indicating potential fluid buildup or infection."
34tokens = tokenizer(text)
35
36# encode to a single embedding
37text_embedding = model.encode_text(tokens)
38print("Individual text embedding size:",text_embedding.shape)
39
40# sequential encoding
41seq_text_embedding = model.text.transformer(tokens, output_hidden_states=True).hidden_states[-1]
42print("Sequential text embedding size:", seq_text_embedding.shape)
431@inproceedings{wang2024unity,
2 title={Unity in Diversity: Collaborative Pre-training Across Multimodal Medical Sources},
3 author={Wang, Xiaochen and Luo, Junyu and Wang, Jiaqi and Zhong, Yuan and Zhang, Xiaokun and Wang, Yaqing and Bhatia, Parminder and Xiao, Cao and Ma, Fenglong},
4 booktitle={Proceedings of the 62nd Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)},
5 pages={3644--3656},
6 year={2024}
7}