File size: 2,154 Bytes
14fbf7f
181f4c3
3c1c6e3
14fbf7f
6c0ff98
 
3c1c6e3
 
181f4c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c3b677
181f4c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
---
library_name: transformers.js
pipeline_tag: zero-shot-image-classification
license: other
tags:
- mobileclip
- image-feature-extraction
- feature-extraction
---

https://github.com/apple/ml-mobileclip with ONNX weights to be compatible with Transformers.js.

## Usage (Transformers.js)

If you haven't already, you can install the [Transformers.js](https://huggingface.co/docs/transformers.js) JavaScript library from [NPM](https://www.npmjs.com/package/@xenova/transformers) using:
```bash
npm i @xenova/transformers
```

**Example:** Perform zero-shot image classification.
```js
import {
  AutoTokenizer,
  CLIPTextModelWithProjection,
  AutoProcessor,
  CLIPVisionModelWithProjection,
  RawImage,
  dot,
  softmax,
} from '@xenova/transformers';

const model_id = 'Xenova/mobileclip_s2';

// Load tokenizer and text model
const tokenizer = await AutoTokenizer.from_pretrained(model_id);
const text_model = await CLIPTextModelWithProjection.from_pretrained(model_id);

// Load processor and vision model
const processor = await AutoProcessor.from_pretrained(model_id);
const vision_model = await CLIPVisionModelWithProjection.from_pretrained(model_id, {
  quantized: false, // NOTE: vision model is sensitive to quantization.
});

// Run tokenization
const texts = ['cats', 'dogs', 'birds'];
const text_inputs = tokenizer(texts, { padding: 'max_length', truncation: true });

// Compute text embeddings
const { text_embeds } = await text_model(text_inputs);
const normalized_text_embeds = text_embeds.normalize().tolist();

// Read image and run processor
const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg';
const image = await RawImage.read(url);
const image_inputs = await processor(image);

// Compute vision embeddings
const { image_embeds } = await vision_model(image_inputs);
const normalized_image_embeds = image_embeds.normalize().tolist();

// Compute probabilities
const probabilities = normalized_image_embeds.map(
  x => softmax(normalized_text_embeds.map(y => 100 * dot(x, y)))
);
console.log(probabilities); // [[ 0.9999973851268408, 0.000002399646544186113, 2.1522661499262862e-7 ]]
```