유사도 기준 정렬
이제 모든 피처에 임베딩을 생성했으니, 다음 단계는 유사도를 계산하는 일입니다. 이번 연습에서는 find_n_closest()라는 함수를 정의해, 쿼리 벡터와 임베딩 리스트 사이의 코사인 거리를 계산하고, 가장 작은 거리 n개와 그 인덱스를 반환하게 만듭니다.
다음 연습에서는 이 함수를 사용해 시맨틱 상품 검색 애플리케이션을 구현해 볼 거예요.
distance는 scipy.spatial에서 이미 임포트되어 있습니다.
이 연습은 강의의 일부입니다
OpenAI API로 시작하는 임베딩 Introduction
연습 안내
query_vector와embedding사이의 코사인 거리를 계산하세요.dist와 그index를 포함한 사전을distances리스트에 추가하세요.- 각 사전의
'distance'키를 기준으로distances리스트를 정렬하세요. distances_sorted에서 처음n개의 요소를 반환하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
def find_n_closest(query_vector, embeddings, n=3):
distances = []
for index, embedding in enumerate(embeddings):
# Calculate the cosine distance between the query vector and embedding
dist = ____
# Append the distance and index to distances
distances.append({"distance": ____, "index": ____})
# Sort distances by the distance key
distances_sorted = ____
# Return the first n elements in distances_sorted
return ____