Nhập môn Embeddings với OpenAI API
Emmanuel Pire
Senior Software Engineer, DataCamp
articles = [
{"headline": "Tăng trưởng kinh tế tiếp diễn giữa bất ổn toàn cầu", "topic": "Business"},
{"headline": "Lãi suất giảm xuống mức thấp kỷ lục", "topic": "Business"},
{"headline": "Các nhà khoa học đạt đột phá về năng lượng tái tạo", "topic": "Science"},
{"headline": "Ấn Độ hạ cánh thành công gần cực Nam của Mặt Trăng", "topic": "Science"},
{"headline": "Phát hiện hạt mới tại CERN", "topic": "Science"},
{"headline": "Công ty công nghệ ra mắt sản phẩm cải thiện khả năng tiếp cận trực tuyến", "topic": "Tech"},
{"headline": "Tập đoàn công nghệ mua 49% cổ phần startup AI", "topic": "Tech"},
{"headline": "Nền tảng mạng xã hội mới khiến mọi người bàn tán!", "topic": "Tech"},
{"headline": "The Blues thăng hạng ở ngày cuối mùa giải!", "topic": "Sport"},
{"headline": "1,5 tỷ người theo dõi chung kết World Cup", "topic": "Sport"}
]

headline_text = [article['headline'] for article in articles]
headline_text
["Tăng trưởng kinh tế tiếp diễn giữa bất ổn toàn cầu",
...,
"1,5 tỷ người theo dõi chung kết World Cup"]
response = client.embeddings.create(
model="text-embedding-3-small",
input=headline_text
)
response_dict = response.model_dump()
[...]
'data': [
{
"embedding": [-0.017142612487077713, ..., -0.0012911480152979493],
"index": 0,
"object": "embedding"
},
{
"embedding": [-0.032995883375406265, ..., -0.0028605300467461348],
"index": 1,
"object": "embedding"
},
...
]
[...]
articles = [
{"headline": "Tăng trưởng kinh tế tiếp diễn giữa bất ổn toàn cầu", "topic": "Business"},
...
]
for i, article in enumerate(articles):article['embedding'] = response_dict['data'][i]['embedding']print(articles[:2])
[{'headline': 'Tăng trưởng kinh tế tiếp diễn giữa bất ổn toàn cầu',
'topic': 'Business',
'embedding': [-0.017142612487077713, ..., -0.0012911480152979493]}
{'headline': 'Lãi suất giảm xuống mức thấp kỷ lục',
'topic': 'Business',
'embedding': [-0.032995883375406265, ..., -0.0028605300467461348]}]
len(articles[0]['embedding'])
1536
len(articles[5]['embedding'])
1536
from sklearn.manifold import TSNE import numpy as npembeddings = [article['embedding'] for article in articles]tsne = TSNE(n_components=2, perplexity=5)embeddings_2d = tsne.fit_transform(np.array(embeddings))
n_components: số chiều đầu raperplexity: tham số của thuật toán, phải nhỏ hơn số điểm dữ liệuimport matplotlib.pyplot as plt plt.scatter(embeddings_2d[:, 0], embeddings_2d[:, 1])topics = [article['topic'] for article in articles] for i, topic in enumerate(topics): plt.annotate(topic, (embeddings_2d[i, 0], embeddings_2d[i, 1])) plt.show()

Nhập môn Embeddings với OpenAI API