Hub documentation

Выполнение поиска по векторному сходству

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Выполнение поиска по векторному сходству

Функция Fixed-Length Arrays была добавлена в DuckDB версии 0.10.0. Это позволяет использовать векторные эмбеддинги в таблицах DuckDB, что делает анализ данных еще более мощным.

Кроме того, была введена функция array_cosine_similarity. Эта функция измеряет косинус угла между двумя векторами, что указывает на их сходство. Значение 1 означает, что векторы идеально совпадают по направлению, 0 — что они перпендикулярны, а -1 — что они направлены в противоположные стороны.

Рассмотрим, как использовать эту функцию для поиска по сходству. В этом разделе мы покажем, как выполнять поиск по сходству с помощью DuckDB.

Мы будем использовать датасет asoria/awesome-chatgpt-prompts-embeddings.

Сначала посмотрим несколько записей из набора данных:

FROM 'hf://datasets/asoria/awesome-chatgpt-prompts-embeddings/data/*.parquet' SELECT act, prompt, len(embedding) as embed_len LIMIT 3;

┌──────────────────────┬──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┬───────────┐
│         act          │                                                                                    prompt                                                                                    │ embed_len │
│       varchar        │                                                                                   varchar                                                                                    │   int64   │
├──────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┼───────────┤
│ Linux Terminal       │ I want you to act as a linux terminal. I will type commands and you will reply with what the terminal should show. I want you to only reply with the terminal output insid…  │       384 │
│ English Translator…  │ I want you to act as an English translator, spelling corrector and improver. I will speak to you in any language and you will detect the language, translate it and answer…  │       384 │
│ `position` Intervi…  │ I want you to act as an interviewer. I will be the candidate and you will ask me the interview questions for the `position` position. I want you to only reply as the inte…  │       384 │
└──────────────────────┴──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┴───────────┘

Далее выберите эмбеддинг, который будет использоваться для поиска по сходству:

FROM 'hf://datasets/asoria/awesome-chatgpt-prompts-embeddings/data/*.parquet' SELECT  embedding  WHERE act = 'Linux Terminal';

┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│                                                                                                    embedding                                                                                                    │
│                                                                                                     float[]                                                                                                     │
├─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤
│ [-0.020781303, -0.029143505, -0.0660217, -0.00932716, -0.02601602, -0.011426172, 0.06627567, 0.11941507, 0.0013917526, 0.012889079, 0.053234346, -0.07380514, 0.04871567, -0.043601237, -0.0025319182, 0.0448…  │
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘

Теперь используем выбранный эмбеддинг, чтобы найти похожие записи:

SELECT act,
       prompt,
       array_cosine_similarity(embedding::float[384], (SELECT embedding FROM 'hf://datasets/asoria/awesome-chatgpt-prompts-embeddings/data/*.parquet' WHERE  act = 'Linux Terminal')::float[384]) AS similarity 
FROM 'hf://datasets/asoria/awesome-chatgpt-prompts-embeddings/data/*.parquet'
ORDER BY similarity DESC
LIMIT 3;

┌──────────────────────┬─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┬────────────┐
│         act          │                                                                                   prompt                                                                                    │ similarity │
│       varchar        │                                                                                   varchar                                                                                   │   float    │
├──────────────────────┼─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┼────────────┤
│ Linux Terminal       │ I want you to act as a linux terminal. I will type commands and you will reply with what the terminal should show. I want you to only reply with the terminal output insi…  │        1.0 │
│ JavaScript Console   │ I want you to act as a javascript console. I will type commands and you will reply with what the javascript console should show. I want you to only reply with the termin…  │  0.7599728 │
│ R programming Inte…  │ I want you to act as a R interpreter. I'll type commands and you'll reply with what the terminal should show. I want you to only reply with the terminal output inside on…  │  0.7303775 │
└──────────────────────┴─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┴────────────┘

Всё готово! Вы успешно выполнили поиск по векторному сходству с помощью DuckDB.

Update on GitHub