1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

タイトルからおすすめを取得するfaissを使ってみた

Last updated at Posted at 2025-12-02

はじめに

この記事ではpythonとfaissというライブラリを使用します
使用したスタック

  • Python3.10
  • Ubuntu 24.04
  • faiss-gpu
  • sentence-transformers
  • numpy
    ※この記事ではGPUを使用しています。NvidiaのGPUがない場合はfaiss-cpuを使用しています。Windowsではfaiss-cpuを使用してください

使用例

image.png
この画像は私の作成している動画配信サイトでの表示ですが、faissを使用することにより視聴履歴から、興味がありそうな画像を選別しています。

実装方法

ここではコードをいくつかに分割して掲載していきます

必要なライブラリをインポート

from sentence_transformers import SentenceTransformer
import faiss
import numpy as np

実際にサイトに導入するにはAPIやコンテンツにあわせて修正が必要ですが、ここでは省いています

必要なAIの初期化

#サンプルコンテンツのリスト
sample_contents = ["test1の意味", "日本語を形態解析してみた", "病理検査の意味解説"]
#AIの初期化
cached_model = SentenceTransformer('all-MiniLM-L6-v2')
embeddings = cached_model.encode(sample_contents, normalize_embeddings=True)
# FAISSインデックスを作成
if len(embeddings.shape) == 1:
    embeddings = embeddings.reshape(1, -1)
dimension = embeddings.shape[1]
cached_index = faiss.IndexFlatIP(dimension)
cached_index.add(embeddings.astype('float32'))

ここではサンプルのリストを構成し、AIに読み込み検索用のインデックスを構成しています。APIで使用するときはモデルの読み込みの処理を事前に行っておくことで高速化を狙えます

推論

次は実際に予測をしていきます

# サンプルの閲覧履歴作成
sample_views = ["病院の仕組みと保険", "3分でわかる経営学", "病理検査の意味解説"]
user_input = " ".join(sample_views)
# user_inputを元に推測
# ユーザー入力をベクトル化
input_embedding = cached_model.encode([user_input], normalize_embeddings=True)
# 実際の予測(ここでは1つだけ取得)
distances, indices = cached_index.search(input_embedding, 1)
recommended = []
idx = indices[0][0]
print("Content:", sample_contents[idx])

このコードを使用するとsample contentから選別されシェルに1つ表示されるはずです。実際の使用にはindices[0]のループが必要です。

最後に

このコードを使用すれば、おすすめ表示やランダムコンテンツが作れるはずです。何かしらのサービスを作る際にはぜひ活用してみてください

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?