Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added command and code for computing euclidian distances between embeddings #58

Merged
merged 1 commit into from
Apr 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions src/ontogpt/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -543,6 +543,33 @@ def text_similarity(text, context, output, model, output_format, **kwargs):
sim = client.similarity(text1, text2, model=model)
print(sim)

@main.command()
@output_option_txt
@output_format_options
@model_option
@click.option(
"-C",
"--context",
help="domain e.g. anatomy, industry, health-related (NOT IMPLEMENTED - currently gene only)",
)
@click.argument("text", nargs=-1)
def text_distance(text, context, output, model, output_format, **kwargs):
"""Embed text, calculate euclidian distance between embeddings."""
if not text:
raise ValueError("Text must be passed")
text = list(text)
if "@" not in text:
raise ValueError("Text must contain @")
ix = text.index("@")
text1 = " ".join(text[:ix])
text2 = " ".join(text[ix + 1 :])
print(text1)
print(text2)
if model is None:
model = "text-embedding-ada-002"
client = OpenAIClient(model=model)
sim = client.euclidian_distance(text1, text2, model=model)
print(sim)

@main.command()
@output_option_txt
Expand Down
4 changes: 4 additions & 0 deletions src/ontogpt/clients/openai_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,5 +151,9 @@ def similarity(self, text1: str, text2: str, **kwargs):
a2 = self.embeddings(text2, **kwargs)
return np.dot(a1, a2) / (np.linalg.norm(a1) * np.linalg.norm(a2))

def euclidian_distance(self, text1: str, text2: str, **kwargs):
a1 = self.embeddings(text1, **kwargs)
a2 = self.embeddings(text2, **kwargs)
return np.linalg.norm(np.array(a1) - np.array(a2))