코드구현

TF-IDF와 Word2Vec기반 Page Rank를 활용한 캡션 중요도 분석

decaf coffee 2024. 12. 1. 20:27

캡션 데이터를 기반으로 TF-IDF 와 Word2Vec 를 활용하여 캡션 간 유사도를 계산하고, 이를 PageRank 알고리즘에 적용하여 각 캡션의 상대적 유사도를 평가한 결과를 제시해볼 예정입니다.

이를 통해 TF-IDF 와 Word2Vec 기반의 유사도 계산 방법을 비교하고 가장 중요한 캡션을 도출해봅시다.

 

데이터

 

분석에 사용된 캡션은 다음과 같습니다.

1. A dog is running through a field.
2. A cat is sitting on a windowsill, enjoying the sunshine.
3. A dog is running and enjoying the sunshine in a field.
4. A rabbit is hopping across a grassy meadow.

 

분석 방법

 

1. TF-IDF를 사용한 유사도 계산

- 각 단어의 빈도 및 문서 내 중요도 기반 문장 벡터화

- 문장 간 코사인 유사도를 계산해 유사도 행렬 생성

 

2. Word2Vec를 사용한 유사도 계산

- 사전 학습된 Google News Word2Vec 모델을 사용해 단어 벡터화

- 각 문장의 단어 벡터 평균을 구해 문장 벡터로 표현

- 문장 간 코사인 유사도를 계산해 유사도 행렬 생성

 

3. PageRank 알고리즘 적용

- TF-IDF 및 Word2Vec 기반 유사도 행렬을 입력으로 받아 PageRank 알고리즘을 통해 각 캡션의 중요도를 계산

 

import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from gensim.models import KeyedVectors
from gensim.utils import simple_preprocess

# PageRank 관련 함수
def normalizeAdjacencyMatrix(A):
    n = len(A)
    for j in range(len(A[0])):
        sumOfCol = sum(A[i][j] for i in range(len(A)))
        if sumOfCol == 0:
            for i in range(n):
                A[i][j] = 1 / n
        else:
            for i in range(n):
                A[i][j] = A[i][j] / sumOfCol
    return A

def dampingMatrix(A, dampingFactor=0.85):
    n = len(A)
    Q = [[1 / n] * n for _ in range(n)]
    arrA = np.array(A)
    arrQ = np.array(Q)
    arrM = dampingFactor * arrA + (1 - dampingFactor) * arrQ
    return arrM

def findSteadyState(M):
    eigenValues, eigenVectors = np.linalg.eig(M)
    idx = np.argmax(np.isclose(eigenValues, 1.0))
    steadyStateVector = eigenVectors[:, idx]
    steadyStateVector = steadyStateVector / sum(steadyStateVector)
    return np.real(steadyStateVector)

def pageRank(A):
    A = normalizeAdjacencyMatrix(A)
    M = dampingMatrix(A)
    return findSteadyState(M)

# 캡션 리스트
captions = [
    "A dog is running through a field.",
    "A cat is sitting on a windowsill, enjoying the sunshine.",
    "A dog is running and enjoying the sunshine in a field.",
    "A rabbit is hopping across a grassy meadow."
]

# 1. TF-IDF를 사용한 유사도 계산
vectorizer = TfidfVectorizer()
tfidf_matrix = vectorizer.fit_transform(captions)
tfidf_similarity_matrix = cosine_similarity(tfidf_matrix)

# 2. Word2Vec 모델 로드
from google.colab import drive
drive.mount('/content/drive')
w2v_model = KeyedVectors.load_word2vec_format("/content/drive/MyDrive/GoogleNews-vectors-negative300.bin.gz", binary=True)

# Word2Vec 벡터화 함수
def sentence_to_vector(sentence, model):
    words = simple_preprocess(sentence)
    word_vectors = [model[word] for word in words if word in model]
    if len(word_vectors) > 0:
        return np.mean(word_vectors, axis=0)
    else:
        return np.zeros(model.vector_size)

# Word2Vec 벡터 변환
word2vec_vectors = [sentence_to_vector(sentence, w2v_model) for sentence in captions]

# Word2Vec 기반 유사도 행렬 계산
word2vec_similarity_matrix = cosine_similarity(word2vec_vectors)

# 3. PageRank 계산 (TF-IDF 기반)
tfidf_page_rank_scores = pageRank(tfidf_similarity_matrix)

# 4. PageRank 계산 (Word2Vec 기반)
word2vec_page_rank_scores = pageRank(word2vec_similarity_matrix)

# 5. 결과 출력
print("TF-IDF 기반 캡션 별 PageRank 점수:")
for i, (caption, score) in enumerate(zip(captions, tfidf_page_rank_scores)):
    print(f"{i+1}. {caption} - PageRank 점수: {score:.4f}")

print("\nWord2Vec 기반 캡션 별 PageRank 점수:")
for i, (caption, score) in enumerate(zip(captions, word2vec_page_rank_scores)):
    print(f"{i+1}. {caption} - PageRank 점수: {score:.4f}")

# TF-IDF와 Word2Vec 결과 비교
tfidf_max_score_index = np.argmax(tfidf_page_rank_scores)
word2vec_max_score_index = np.argmax(word2vec_page_rank_scores)

print("\nTF-IDF 기반 가장 중요한 캡션:")
print(captions[tfidf_max_score_index])

print("\nWord2Vec 기반 가장 중요한 캡션:")
print(captions[word2vec_max_score_index])

 

결과

 

TF-IDF 기반 PageRank 점수:

1. A dog is running through a field. - PageRank 점수: 0.2538
2. A cat is sitting on a windowsill, enjoying the sunshine. - PageRank 점수: 0.2369
3. A dog is running and enjoying the sunshine in a field. - PageRank 점수: 0.2891
4. A rabbit is hopping across a grassy meadow. - PageRank 점수: 0.2202

 

Word2Vec 기반 PageRank 점수:

1. A dog is running through a field. - PageRank 점수: 0.2469
2. A cat is sitting on a windowsill, enjoying the sunshine. - PageRank 점수: 0.2497
3. A dog is running and enjoying the sunshine in a field. - PageRank 점수: 0.2679
4. A rabbit is hopping across a grassy meadow. - PageRank 점수: 0.2355

 

결론

 

TF-IDF 와 Word2Vec 두 방법 모두 문장 간 유사도를 기반으로 PageRank 알고리즘을 적용해 캡션의 중요도를 평가하는 데 유용합니다.Word2Vec 기반 분석은 단어간 의미적 관계를 포함하여 유사도를 계산하므로, TF-IDF 보다 더 정교한 결과를 제공할 수 있습니다. 두 방법 모두 "A dog is running and enjoying the sunshine in a field" 를 가장  중요한 캡션으로 평가해 신뢰성을 확인할 수 있었습니다.