feat: solution for '8. Самописный поисковый агент на основе deep agents from scratch'
This commit is contained in:
@@ -1,95 +1,76 @@
|
||||
# Самописный поисковый агент на основе deep agents from scratch
|
||||
# Deep Agent Search with Virtual File System
|
||||
|
||||
## Описание
|
||||
This project demonstrates a simple deep agent search system that operates on **virtual files** stored entirely in memory. It uses **PyTorch**, **scikit-learn**, and **NumPy** to perform TF‑IDF vectorization and cosine similarity ranking.
|
||||
|
||||
Данный репозиторий содержит простую реализацию поискового агента, построенного с нуля с использованием глубоких нейронных сетей. Агент:
|
||||
## Features
|
||||
|
||||
- **Преобразует** запросы и документы в TF‑IDF векторы.
|
||||
- **Обучается** на паре запрос‑документ с метками релевантности, используя логистическую регрессию (один линейный слой).
|
||||
- **Оценивает** точность и полноту на тестовом наборе.
|
||||
- **Возвращает** топ‑k наиболее релевантных документов для любого запроса.
|
||||
- **Virtual File System**: Create, read, write, unload, and delete virtual files.
|
||||
- **Search Agent**: Rank lines from a virtual file based on a query using TF‑IDF and cosine similarity.
|
||||
- **Deep Learning Integration**: Uses PyTorch tensors for similarity calculations.
|
||||
- **Easy to Extend**: Replace the search logic with more sophisticated models (e.g., transformers) without changing the file system.
|
||||
|
||||
### Технологии
|
||||
|
||||
- Python 3.8+
|
||||
- PyTorch
|
||||
- scikit‑learn
|
||||
- NumPy
|
||||
|
||||
## Установка
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
# Клонируйте репозиторий
|
||||
git clone https://git.brojs.ru/kuzakhmetovartur/8.-samopisnyy-poiskovyy-agent-na-osnove.git
|
||||
cd 8.-samopisnyy-poiskovyy-agent-na-osnove
|
||||
# Clone the repository
|
||||
git clone https://git.brojs.ru/kuzakhmetovartur/8.-samopisnyy-poiskovyy-agent-na-osnove-
|
||||
cd 8.-samopisnyy-poiskovyy-agent-na-osnove-
|
||||
|
||||
# Создайте виртуальное окружение (рекомендуется)
|
||||
# Create a virtual environment (optional but recommended)
|
||||
python -m venv venv
|
||||
source venv/bin/activate # Windows: venv\Scripts\activate
|
||||
source venv/bin/activate # On Windows: venv\Scripts\activate
|
||||
|
||||
# Установите зависимости
|
||||
# Install dependencies
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
`requirements.txt` содержит:
|
||||
## Usage
|
||||
|
||||
```
|
||||
torch>=1.7.0
|
||||
scikit-learn>=0.24
|
||||
numpy>=1.19
|
||||
```
|
||||
|
||||
## Использование
|
||||
|
||||
### Демонстрация
|
||||
Run the example script:
|
||||
|
||||
```bash
|
||||
python src/index.py
|
||||
python src/main.py
|
||||
```
|
||||
|
||||
Вы увидите вывод обучения, оценку точности/полноты и пример поиска.
|
||||
You should see output similar to:
|
||||
|
||||
### Интеграция в свой проект
|
||||
|
||||
```python
|
||||
from src.index import SearchAgent
|
||||
|
||||
documents = [
|
||||
"Документ 1",
|
||||
"Документ 2",
|
||||
# ...
|
||||
]
|
||||
|
||||
agent = SearchAgent(documents)
|
||||
|
||||
# Обучаем
|
||||
queries = ["Какой вопрос?", "Что такое AI?"]
|
||||
relevance = [[0], [1]] # индексы релевантных документов
|
||||
agent.train_agent(queries, relevance, epochs=10)
|
||||
|
||||
# Оцениваем
|
||||
precision, recall = agent.evaluate(queries, relevance)
|
||||
|
||||
# Поиск
|
||||
results = agent.search("Новый запрос", top_k=3)
|
||||
for doc, score in results:
|
||||
print(f"{score:.4f} - {doc}")
|
||||
```
|
||||
Search results for query: 'neural networks'
|
||||
1. Neural networks can approximate complex functions.
|
||||
2. Deep learning has revolutionized many fields.
|
||||
3. PyTorch provides dynamic computation graphs.
|
||||
After unload: Cannot read from unloaded file 'sample.txt'.
|
||||
```
|
||||
|
||||
## Тесты
|
||||
## Project Structure
|
||||
|
||||
Тесты находятся в `tests/` (если добавлены). Запуск:
|
||||
|
||||
```bash
|
||||
pytest tests/
|
||||
```
|
||||
├── src
|
||||
│ ├── main.py # Entry point and demo
|
||||
│ └── virtual_file_system.py # Virtual file system implementation
|
||||
├── requirements.txt # Dependencies
|
||||
└── README.md # Documentation
|
||||
```
|
||||
|
||||
## Ограничения
|
||||
## Extending the Search Agent
|
||||
|
||||
- Модель использует только один линейный слой, поэтому не может захватывать сложные взаимосвязи.
|
||||
- Размерность TF‑IDF может быть большой; для больших наборов данных стоит использовать более эффективные методы векторизации.
|
||||
- В примере используется синтетический набор данных; для реальных задач потребуется более крупный датасет и более сложная модель.
|
||||
The `SearchAgent` class in `src/main.py` can be replaced with any model that accepts a query and returns ranked results. For example, you could:
|
||||
|
||||
## Лицензия
|
||||
- Load a pre‑trained transformer (e.g., BERT) and compute embeddings.
|
||||
- Use a neural ranking model trained on relevance data.
|
||||
- Integrate with external search APIs.
|
||||
|
||||
MIT License
|
||||
Just ensure that the agent receives a `VirtualFileSystem` instance and uses `VirtualFile.read()` to access data.
|
||||
|
||||
## Testing
|
||||
|
||||
Unit tests are not included in this minimal example, but you can add tests using `pytest` to verify:
|
||||
|
||||
- Virtual file read/write/unload behavior.
|
||||
- Search agent ranking correctness.
|
||||
- Integration of the virtual file system with the agent.
|
||||
|
||||
## License
|
||||
|
||||
MIT License
|
||||
```
|
||||
Reference in New Issue
Block a user