<jupyter_start><jupyter_text>Visualizing the embeddings in 3D The example uses [PCA](https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html) to reduce the dimensionality fo the embeddings from 2048 to 3. Then we can visualize the data points in a 3D plot. The small dataset `dbpedia_samples.jsonl` is curated by randomly sampling 200 samples from [DBpedia validation dataset](https://www.kaggle.com/danofer/dbpedia-classes?select=DBPEDIA_val.csv).  1. Load the dataset and query embeddings<jupyter_code>import pandas as pd
samples = pd.read_json("dbpedia_samples.jsonl", lines=True)
categories = sorted(samples["category"].unique())
print("Categories of DBpedia samples:", samples["category"].value_counts())
samples.head()
from openai.embeddings_utils import get_embeddings
# NOTE: The following code will send a query of batch size 200 to /embeddings, cost about $0.2
matrix = get_embeddings(samples["text"].to_list(), engine="text-similarity-babbage-001")<jupyter_output><empty_output><jupyter_text>2. Reduce the embedding dimensionality<jupyter_code>from sklearn.decomposition import PCA
pca = PCA(n_components=3)
vis_dims = pca.fit_transform(matrix)
samples["embed_vis"] = vis_dims.tolist()<jupyter_output><empty_output><jupyter_text>3. Plot the embeddings of lower dimensionality<jupyter_code>%matplotlib widget
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize=(10, 5))
ax = fig.add_subplot(projection='3d')
cmap = plt.get_cmap("tab20")

# Plot each sample category individually such that we can set label name.
for i, cat in enumerate(categories):
    sub_matrix = np.array(samples[samples["category"] == cat]["embed_vis"].to_list())
    x=sub_matrix[:, 0]
    y=sub_matrix[:, 1]
    z=sub_matrix[:, 2]
    colors = [cmap(i/len(categories))] * len(sub_matrix)
    ax.scatter(x, y, zs=z, zdir='z', c=colors, label=cat)

ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
ax.legend(bbox_to_anchor=(1.1, 1))<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12643678160919541, 'fraction_numerical': 0.01699150424787606, 'mean_word_length': 6.583333333333333, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 2, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '224406', 'license': 'MIT', 'n_tokens_mistral': 706, 'n_tokens_neox': 679, 'n_words': 166, 'path': 'examples/embeddings/Visualize_in_3d.ipynb', 'repo_name': 'sorinsuciu-msft/openai-python', 'size': '2001'}