Ultralytics Explorer API#
ultralytics>=8.3.12 시점부터 Ultralytics Explorer는 제거되었습니다. Explorer를 사용하려면 pip install ultralytics==8.3.11을(를) 설치하세요. 유사한 (그리고 확장된) 데이터셋 탐색 기능은 Ultralytics Platform에서 사용할 수 있습니다.
소개#
The Explorer API is a Python API for exploring your datasets. It supports filtering and searching your dataset using SQL queries, vector similarity search, and semantic search.
Watch: Ultralytics Explorer API Overview
설치#
Explorer는 일부 기능을 위해 외부 라이브러리에 의존합니다. 이러한 종속성은 Explorer를 사용할 때 자동으로 설치됩니다. 이러한 종속성을 수동으로 설치하려면 다음 명령을 사용하세요.
pip install ultralytics[explorer]사용법#
from ultralytics import Explorer
# Create an Explorer object
explorer = Explorer(data="coco128.yaml", model="yolo11n.pt")
# Create embeddings for your dataset
explorer.create_embeddings_table()
# Search for similar images to a given image/images
df = explorer.get_similar(img="path/to/image.jpg")
# Or search for similar images to a given index/indices
df = explorer.get_similar(idx=0)지정된 데이터셋 및 모델 쌍에 대한 Embeddings 테이블은 한 번만 생성되며 재사용됩니다. 내부적으로 디스크 확장이 가능한 LanceDB를 사용하므로, 메모리 부족 없이 COCO와 같은 대규모 데이터셋에 대한 임베딩을 생성하고 재사용할 수 있습니다.
임베딩 테이블을 강제로 업데이트하려면 force=True을 create_embeddings_table 메서드에 전달할 수 있습니다.
고급 분석을 수행하기 위해 LanceDB 테이블 객체에 직접 액세스할 수 있습니다. Working with Embeddings Table section에서 자세히 알아보세요.
1. 유사도 검색#
유사도 검색은 주어진 이미지와 유사한 이미지를 찾는 기법입니다. 유사한 이미지는 유사한 임베딩을 가질 것이라는 아이디어에 기반합니다. 임베딩 테이블이 구축되면 다음 방법 중 하나로 시맨틱 검색을 실행할 수 있습니다:
- 데이터셋의 특정 인덱스 또는 인덱스 목록에서:
exp.get_similar(idx=[1,10], limit=10) - 데이터셋에 없는 임의의 이미지 또는 이미지 목록에서:
exp.get_similar(img=["path/to/img1", "path/to/img2"], limit=10)
여러 개의 입력이 있는 경우, 해당 임베딩들의 집합(aggregate)이 사용됩니다.
입력 데이터와 가장 유사한 데이터 포인트 limit개와 임베딩 공간에서의 거리가 포함된 pandas DataFrame을 얻게 됩니다. 이 데이터셋을 사용하여 추가 필터링을 수행할 수 있습니다.
from ultralytics import Explorer
# create an Explorer object
exp = Explorer(data="coco128.yaml", model="yolo11n.pt")
exp.create_embeddings_table()
similar = exp.get_similar(img="https://ultralytics.com/images/bus.jpg", limit=10)
print(similar.head())
# Search using multiple indices
similar = exp.get_similar(
img=["https://ultralytics.com/images/bus.jpg", "https://ultralytics.com/images/bus.jpg"],
limit=10,
)
print(similar.head())유사 이미지 시각화#
또한 plot_similar 메서드를 사용하여 유사한 이미지를 시각화할 수 있습니다. 이 메서드는 get_similar과(와) 동일한 인수를 받아 유사한 이미지들을 그리드 형태로 플롯합니다.
from ultralytics import Explorer
# create an Explorer object
exp = Explorer(data="coco128.yaml", model="yolo11n.pt")
exp.create_embeddings_table()
plt = exp.plot_similar(img="https://ultralytics.com/images/bus.jpg", limit=10)
plt.show()2. AI에게 질문하기 (자연어 쿼리)#
이 기능을 사용하면 SQL을 작성하지 않고도 자연어로 데이터셋을 필터링할 수 있습니다. AI 기반 쿼리 생성기가 프롬프트를 쿼리로 변환하여 일치하는 결과를 반환합니다. 예를 들어, "사람 정확히 1명과 개 2마리가 있는 이미지 100장을 보여줘. 다른 객체가 있어도 돼"라고 요청하면 쿼리를 생성하여 해당 결과를 보여줍니다. 참고: 이 기능은 LLM을 사용하므로 결과가 확률적이며 정확하지 않을 수 있습니다.
from ultralytics.data.explorer import plot_query_result
from ultralytics import Explorer
# create an Explorer object
exp = Explorer(data="coco128.yaml", model="yolo11n.pt")
exp.create_embeddings_table()
df = exp.ask_ai("show me 100 images with exactly one person and 2 dogs. There can be other objects too")
print(df.head())
# plot the results
plt = plot_query_result(df)
plt.show()3. SQL 쿼리#
sql_query 메서드를 사용하여 데이터셋에서 SQL 쿼리를 실행할 수 있습니다. 이 메서드는 SQL 쿼리를 입력으로 받아 결과가 포함된 pandas DataFrame을 반환합니다.
from ultralytics import Explorer
# create an Explorer object
exp = Explorer(data="coco128.yaml", model="yolo11n.pt")
exp.create_embeddings_table()
df = exp.sql_query("WHERE labels LIKE '%person%' AND labels LIKE '%dog%'")
print(df.head())SQL 쿼리 결과 시각화#
또한 plot_sql_query 메서드를 사용하여 SQL 쿼리 결과를 플롯할 수 있습니다. 이 메서드는 sql_query과(와) 동일한 인수를 받아 결과를 그리드 형태로 플롯합니다.
from ultralytics import Explorer
# create an Explorer object
exp = Explorer(data="coco128.yaml", model="yolo11n.pt")
exp.create_embeddings_table()
# plot the SQL Query
exp.plot_sql_query("WHERE labels LIKE '%person%' AND labels LIKE '%dog%' LIMIT 10")4. Embeddings 테이블 작업#
임베딩 테이블을 직접 조작할 수도 있습니다. 임베딩 테이블이 생성되면 Explorer.table을(를) 사용하여 액세스할 수 있습니다.
Explorer는 내부적으로 LanceDB 테이블을 기반으로 작동합니다. Explorer.table 객체를 사용하여 이 테이블에 직접 액세스하고 원시 쿼리를 실행하거나, 사전 및 사후 필터를 푸시다운하는 등의 작업을 수행할 수 있습니다.
from ultralytics import Explorer
exp = Explorer()
exp.create_embeddings_table()
table = exp.table테이블로 수행할 수 있는 몇 가지 예시는 다음과 같습니다:
원시 Embeddings 가져오기#
from ultralytics import Explorer
exp = Explorer()
exp.create_embeddings_table()
table = exp.table
embeddings = table.to_pandas()["vector"]
print(embeddings)사전 및 사후 필터를 활용한 고급 쿼리#
from ultralytics import Explorer
exp = Explorer(model="yolo11n.pt")
exp.create_embeddings_table()
table = exp.table
# Dummy embedding
embedding = [i for i in range(256)]
rs = table.search(embedding).metric("cosine").where("").limit(10)벡터 인덱스 생성#
대규모 데이터셋을 사용할 때는 더 빠른 쿼리를 위해 전용 벡터 인덱스를 생성할 수도 있습니다. 이는 LanceDB 테이블에서 create_index 메서드를 사용하여 수행합니다.
table.create_index(num_partitions=..., num_sub_vectors=...)5. Embeddings 활용 사례#
Embeddings 테이블을 사용하여 다양한 탐색적 분석을 수행할 수 있습니다. 몇 가지 예시는 다음과 같습니다:
유사도 인덱스#
Explorer에는 similarity_index 작업이 포함되어 있습니다:
- 각 데이터 포인트가 나머지 데이터셋과 얼마나 유사한지 추정하려고 시도합니다.
- 이 작업은 생성된 임베딩 공간에서 현재 이미지보다
max_dist보다 더 가깝게 위치한 이미지 임베딩의 개수를 세는 방식으로 수행되며, 한 번에top_k개의 유사한 이미지를 고려합니다.
다음 열이 포함된 pandas DataFrame을 반환합니다:
idx: 데이터셋 내 이미지의 인덱스im_file: 이미지 파일 경로count: 현재 이미지와의 거리가max_dist보다 가까운 데이터셋 내 이미지의 수sim_im_files:count유사 이미지들의 경로 목록
주어진 데이터셋, 모델, max_dist 및 top_k에 대해 한 번 생성된 유사도 인덱스는 재사용됩니다. 데이터셋이 변경되었거나 단순히 유사도 인덱스를 다시 생성해야 하는 경우 force=True를(을) 전달할 수 있습니다.
from ultralytics import Explorer
exp = Explorer()
exp.create_embeddings_table()
sim_idx = exp.similarity_index()유사도 인덱스를 사용하여 데이터셋을 필터링하는 사용자 지정 조건을 빌드할 수 있습니다. 예를 들어, 다음 코드를 사용하여 데이터셋의 다른 어떤 이미지와도 유사하지 않은 이미지를 필터링해낼 수 있습니다:
import numpy as np
sim_count = np.array(sim_idx["count"])
sim_idx["im_file"][sim_count > 30]임베딩 공간 시각화#
선호하는 시각화 도구를 사용하여 임베딩 공간을 시각화할 수도 있습니다. 예를 들어 Matplotlib을 사용한 간단한 예시는 다음과 같습니다:
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
# Reduce dimensions using PCA to 3 components for visualization in 3D
pca = PCA(n_components=3)
reduced_data = pca.fit_transform(embeddings)
# Create a 3D scatter plot using Matplotlib Axes3D
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection="3d")
# Scatter plot
ax.scatter(reduced_data[:, 0], reduced_data[:, 1], reduced_data[:, 2], alpha=0.5)
ax.set_title("3D Scatter Plot of Reduced 256-Dimensional Data (PCA)")
ax.set_xlabel("Component 1")
ax.set_ylabel("Component 2")
ax.set_zlabel("Component 3")
plt.show()Explorer API를 사용하여 자신만의 CV 데이터셋 탐색 보고서를 만들어 보세요. 영감을 얻으려면 VOC Exploration Example을(를) 확인해 보세요.
Ultralytics Explorer로 빌드된 앱#
Explorer API를 기반으로 하는 GUI Demo를 체험해 보세요.
FAQ#
Ultralytics Explorer API는 포괄적인 데이터셋 탐색을 위해 설계되었습니다. 사용자는 SQL 쿼리, 벡터 유사도 검색 및 시맨틱 검색을 사용하여 데이터셋을 필터링하고 검색할 수 있습니다. 이 강력한 Python API는 대규모 데이터셋을 처리할 수 있으므로, Ultralytics 모델을 사용하는 다양한 computer vision 작업에 이상적입니다.
의존성과 함께 Ultralytics Explorer API를 설치하려면 다음 명령어를 사용하세요:
pip install ultralytics[explorer]이렇게 하면 Explorer API 기능에 필요한 모든 외부 라이브러리가 자동으로 설치됩니다. 추가 설정 세부정보는 당사 문서의 installation section을참조하세요.
Ultralytics Explorer API를 사용하면 임베딩 테이블을 생성하고 유사한 이미지를 쿼리하여 유사도 검색을 수행할 수 있습니다. 기본적인 예시는 다음과 같습니다:
from ultralytics import Explorer # Create an Explorer object explorer = Explorer(data="coco128.yaml", model="yolo11n.pt") explorer.create_embeddings_table() # Search for similar images to a given image similar_images_df = explorer.get_similar(img="path/to/image.jpg") print(similar_images_df.head())자세한 내용은 Similarity Search section을(를) 방문해 주세요.
Ultralytics Explorer가 내부적으로 사용하는 LanceDB는 확장 가능한 디스크 상의 임베딩 테이블을 제공합니다. 이를 통해 메모리 부족 현상 없이 COCO와 같은 대규모 데이터셋에 대한 임베딩을 생성하고 재사용할 수 있습니다. 이러한 테이블은 한 번만 생성되며 재사용될 수 있어 데이터 처리 효율성이 향상됩니다.
AI에게 질문하기 기능을 사용하면 사용자가 자연어 쿼리를 사용하여 데이터셋을 필터링할 수 있습니다. 이 기능은 LLM을 활용하여 내부적으로 이러한 쿼리를 SQL 쿼리로 변환합니다. 예시는 다음과 같습니다:
from ultralytics import Explorer # Create an Explorer object explorer = Explorer(data="coco128.yaml", model="yolo11n.pt") explorer.create_embeddings_table() # Query with natural language query_result = explorer.ask_ai("show me 100 images with exactly one person and 2 dogs. There can be other objects too") print(query_result.head())더 많은 예제를 보려면 Ask AI section을(를) 확인해 보세요.