| 관련성 슬랙에서 토론하십시오
SearchArray는 Pandas 문자열 열을 용어 색인으로 바꿉니다. 그것은 효율적인 BM25 / TFIDF 문구 및 개별 토큰의 점수를 얻습니다.
루센을 생각하지만 팬더 칼럼으로 생각하십시오.
from searcharray import SearchArray
import pandas as pd
df [ 'title_indexed' ] = SearchArray . index ( df [ 'title' ])
np . sort ( df [ 'title_indexed' ]. array . score ([ 'cat' , 'in' , 'the' , 'hat' ])) # Search w/ phrase
> BM25 scores :
> array ([ 0. , 0. , 0. , ..., 15.84568033 , 15.84568033 , 15.84568033 ])SearchArray는이 노트에 문서화되어 있습니다.
SearchArray 가이드 | SearchArray 오프라인 실험 | 내부에 대해
pip install searcharray
def tokenize(value: str) -> List[str] )을 전달하십시오.data_dir 전달하여 메모리 맵파이썬 데이터 스택에서 어휘 검색을 단순화합니다.
많은 ML / AI 실무자들이 벡터 검색 솔루션에 도달 한 다음 어느 정도의 BM25 / 어휘 검색으로 뿌려야한다는 것을 깨달았습니다. 데이터 스택의 다른 부분처럼 전통적인 전체 텍스트 검색을 수행하겠습니다.
SearchArray는 팬더스 배열의 일부로 검색 인덱스를 작성하고 사용하는 판다 중심적인 방법을 만듭니다. 어떤 의미에서, 그것은 팬더로 검색 엔진을 구축하여 외부 시스템없이 모든 사람이 아이디어를 프로토 타입 아이디어와 재창조 할 수 있도록합니다.
이 Colab 노트북에서 전체 엔드 투 엔드 검색 관련 실험을 볼 수 있습니다.
즉, 영화 제목 및 개요와 같은 많은 텍스트가있는 데이터 프레임을 가져 가자.
In[1]: df = pd.DataFrame({'title': titles, 'overview': overviews}, index=ids)
Out[1]:
title overview
374430 Black Mirror: White Christmas This feature-length special consists of three ...
19404 The Brave-Hearted Will Take the Bride Raj is a rich, carefree, happy-go-lucky second...
278 The Shawshank Redemption Framed in the 1940s for the double murder of h...
372058 Your Name. High schoolers Mitsuha and Taki are complete s...
238 The Godfather Spanning the years 1945 to 1955, a chronicle o...
... ... ...
65513 They Came Back The lives of the residents of a small French t...
65515 The Eleventh Hour An ex-Navy SEAL, Michael Adams, (Matthew Reese...
65521 Pyaar Ka Punchnama Outspoken and overly critical Nishant Agarwal ...
32767 Romero Romero is a compelling and deeply moving look ...
텍스트 색인 :
In[2]: df['title_indexed'] = SearchArray.index(df['title'])
df
Out[2]:
title overview title_indexed
374430 Black Mirror: White Christmas This feature-length special consists of three ... Terms({'Black', 'Mirror:', 'White'...
19404 The Brave-Hearted Will Take the Bride Raj is a rich, carefree, happy-go-lucky second... Terms({'The', 'Brave-Hearted', 'Wi...
278 The Shawshank Redemption Framed in the 1940s for the double murder of h... Terms({'The', 'Shawshank', 'Redemp...
372058 Your Name. High schoolers Mitsuha and Taki are complete s... Terms({'Your', 'Name.'}, {'Your': ...
238 The Godfather Spanning the years 1945 to 1955, a chronicle o... Terms({'The', 'Godfather'}, {'The'...
... ... ... ...
65513 They Came Back The lives of the residents of a small French t... Terms({'Back', 'They', 'Came'},...
65515 The Eleventh Hour An ex-Navy SEAL, Michael Adams, (Matthew Reese... Terms({'The', 'Hour', 'Eleventh': ...
65521 Pyaar Ka Punchnama Outspoken and overly critical Nishant Agarwal ... Terms({'Ka', 'Pyaar', 'Punchnama':...
32767 Romero Romero is a compelling and deeply moving look ... Terms({'Romero'})
65534 Poison Paul Braconnier and his wife Blandine only hav... Terms({'Poison'})```
(멍청한 토큰 화에 주목하십시오 - 걱정할 필요가 없습니다.
그런 다음 검색하고 Cat 와 함께 N을 얻습니다
In[3]: np.sort(df['title_indexed'].array.score('Cat'))
Out[3]: array([ 0. , 0. , 0. , ..., 15.84568033,
15.84568033, 15.84568033])
In[4]: df['title_indexed'].score('Cat').argsort()
Out[4]:
array([0, 18561, 18560, ..., 15038, 19012, 4392])
그리고 그냥 팬더 이후로, 우리는 물론 최고 경기를 검색 할 수 있습니다.
In[5]: df.iloc[top_n_cat[-10:]]
Out[5]:
title overview title_indexed
24106 The Black Cat American honeymooners in Hungary are trapped i... Terms({'Black': 1, 'The': 1, 'Cat': 1}, ...
12593 Fritz the Cat A hypocritical swinging college student cat ra... Terms({'Cat': 1, 'the': 1, 'Fritz': 1}, ...
39853 The Cat Concerto Tom enters from stage left in white tie and ta... Terms({'The': 1, 'Cat': 1, 'Concerto': 1...
75491 The Rabbi's Cat Based on the best-selling graphic novel by Joa... Terms({'The': 1, 'Cat': 1, "Rabbi's": 1}...
57353 Cat Run When a sexy, high-end escort holds the key evi... Terms({'Cat': 1, 'Run': 1}, {'Cat': [0],...
25508 Cat People Sketch artist Irena Dubrovna (Simon) and Ameri... Terms({'Cat': 1, 'People': 1}, {'Cat': [...
11694 Cat Ballou A woman seeking revenge for her murdered fathe... Terms({'Cat': 1, 'Ballou': 1}, {'Cat': [...
25078 Cat Soup The surreal black comedy follows Nyatta, an an... Terms({'Cat': 1, 'Soup': 1}, {'Cat': [0]...
35888 Cat Chaser A Miami hotel owner finds danger when be becom... Terms({'Cat': 1, 'Chaser': 1}, {'Cat': [...
6217 Cat People After years of separation, Irina (Nastassja Ki... Terms({'Cat': 1, 'People': 1}, {'Cat': [...
Colab 노트에서 더 많은 사용 사례를 볼 수 있습니다.
전반적인 목표는 Solr 또는 Elasticsearch와 같은 검색 엔진의 많은 어휘 기능 (용어 / 문구 검색)을 재현하지만 Pandas Dataframe에서 재현하는 것입니다.
우리는 가능한 한 검색 할 때 인덱스가 메모리 효율적이고 빠르게되기를 원합니다. 우리는 그것을 사용하여 최소한의 오버 헤드를 갖기를 원합니다.
오프라인 평가를 위해 합리적인 데이터 세트 (100x-1m 문서)를 상대적으로 효율적으로 작업 할 수 있기를 바랍니다. 서비스에서 빠른 재창조를위한 1000s.
'빅 데이터'를 구축하는 대신 우리의 목표는 작은 데이터를 구축하는 것입니다. 즉, 확장 성을 선호하는 기능을 제한하는 팬더의 기능과 표현력에 중점을 둡니다.
이를 위해 SearchArray의 응용은 실험 및 최고 N 후보 재고에 중점을 두는 경향이 있습니다. 실험을 위해, 우리는 팬더로 표현 된 아이디어가 고전 어휘 검색 엔진에서 구현되는 방식에 대해 다소 명확한 경로 / "계약"을 갖기를 원합니다. 재고를 위해서는 기본 시스템에서 일부 상단 N 결과를로드하여 수정할 수 있습니다.
우리는 검색, 헝겊 및 기타 검색 문제 하이브리드 검색 기술이 지배적으로 알고 있습니다. 그러나 종종 대부분의 데이터 과학자들이 벡터 데이터베이스에 합류하는 사람들에게 이상하게 보이는 거대하고 이상한 빅 데이터 어휘 검색 엔진의 관점에서 주조된다. 우리는 어휘 검색이 데이터 과학자와 ML 엔지니어들에게 더 접근하기 쉽기를 원합니다.
파이썬 라이브러리는 이미 토큰 화를 잘하고 있습니다. 루센이 할 수있는 일을 초과하더라도 ... 루센의 토큰 화 능력을 시뮬레이션 및/또는 초과 할 수있는 능력을 제공합니다.
SearchArray에서 토큰 화기는 함수가 문자열을 취하고 일련의 토큰을 방출합니다. 즉, 멍청한, 기본 공백 토큰 화 :
def ws_tokenizer ( string ):
return string . split ()이 서명과 일치하는 토큰 화기를 통과시킬 수 있습니다.
def ws_lowercase_tokenizer ( string ):
return string . lower (). split ()
df [ 'title_indexed' ] = SearchArray . index ( df [ 'title' ], tokenizer = ws_lowercase_tokenizer )줄기 라이브러리 또는 원하는 파이썬 기능을 사용하여 직접 만듭니다.
Solr에는 고유 한 기능 쿼리 syntaxhttps : //solr.apache.org/guide/7_7/function-queries.html이 있습니다. Elasticsearch는 고통이 없습니다.
이것들을 재현하는 대신 기존 팬더 열에서 팬더를 사용하십시오. 그런 다음 나중에 Solr 또는 Elasticsearch에서이를 구현 해야하는 경우 기능을 재현하십시오. 틀림없이 Solr / es에있는 것은 팬더에서 할 수있는 것의 하위 집합 일 것입니다.
# Calculate the number of hours into the past
df['hrs_into_past'] = (now - df['timestamp']).dt.total_seconds() / 3600
원하는 경우 BM25를 곱하십시오.
df['score'] = df['title_indexed'].score('Cat') * df['hrs_into_past']
우리는 어휘, 즉 "BM25-ish"및 인접한 문제에 중점을 둡니다. 벡터 검색을위한 다른 훌륭한 도구가 있습니다.
관련성 Slack의 #SearchArray 채널을 방문하십시오