본문 바로가기
Python Library/Keras

[Keras] 멀티모달 함의 분류 (1)

by goatlab 2024. 3. 30.
728x90
반응형
SMALL

멀티모달 함의 분류

 

멀티모달 함의를 예측하기 위한 모델을 구축하고 훈련한다. Google Research에서 소개한 다중 모드 수반성 데이터 세트 multimodal entailment dataset를 사용한다.

 

멀티모달 함의란 소셜 미디어 플랫폼에서는 콘텐츠를 감사하고 중간 정도의 콘텐츠를 제공하기 위해 거의 실시간으로 다음 질문에 대한 답을 찾고자 할 수 있다.

 

  • 주어진 정보는 다른 정보와 모순 (contradict) 되는지?
  • 주어진 정보는 다른 정보를 의미 ( imply)하는지?

 

자연어 처리에서 이 작업은 텍스트 함의 분석이라고 한다. 이것은 정보가 텍스트 콘텐츠에서 나올 때만 해당된다. 실제로 사용 가능한 정보는 텍스트 콘텐츠뿐만 아니라 텍스트, 이미지, 오디오, 비디오 등의 멀티모달 조합에서 나오는 경우가 많다. 멀티모달 함의는 단순히 텍스트 수반성을 다양한 새로운 입력 양식으로 확장하는 것이다.

라이브러리

 

pip install tensorflow==2.15.0
!pip install -q tensorflow_text
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import os
import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_text as text
from tensorflow import keras
from sklearn.model_selection import train_test_split

 

전처리

 

# Define a label map
label_map = {"Contradictory": 0, "Implies": 1, "NoEntailment": 2}
image_base_path = keras.utils.get_file(
    "tweet_images",
    "https://github.com/sayakpaul/Multimodal-Entailment-Baseline/releases/download/v1.0.0/tweet_images.tar.gz",
    untar=True,
)
df = pd.read_csv(
    "https://github.com/sayakpaul/Multimodal-Entailment-Baseline/raw/main/csvs/tweets.csv"
)
df.sample(10)

 

images_one_paths = []
images_two_paths = []

for idx in range(len(df)):
    current_row = df.iloc[idx]
    id_1 = current_row["id_1"]
    id_2 = current_row["id_2"]
    extentsion_one = current_row["image_1"].split(".")[-1]
    extentsion_two = current_row["image_2"].split(".")[-1]

    image_one_path = os.path.join(image_base_path, str(id_1) + f".{extentsion_one}")
    image_two_path = os.path.join(image_base_path, str(id_2) + f".{extentsion_two}")

    images_one_paths.append(image_one_path)
    images_two_paths.append(image_two_path)

df["image_1_path"] = images_one_paths
df["image_2_path"] = images_two_paths

# Create another column containing the integer ids of
# the string labels.
df["label_idx"] = df["label"].apply(lambda x: label_map[x])

 

시각화

 

def visualize(idx):
    current_row = df.iloc[idx]
    image_1 = plt.imread(current_row["image_1_path"])
    image_2 = plt.imread(current_row["image_2_path"])
    text_1 = current_row["text_1"]
    text_2 = current_row["text_2"]
    label = current_row["label"]

    plt.subplot(1, 2, 1)
    plt.imshow(image_1)
    plt.axis("off")
    plt.title("Image One")
    plt.subplot(1, 2, 2)
    plt.imshow(image_1)
    plt.axis("off")
    plt.title("Image Two")
    plt.show()

    print(f"Text one: {text_1}")
    print(f"Text two: {text_2}")
    print(f"Label: {label}")

random_idx = np.random.choice(len(df))
visualize(random_idx)

random_idx = np.random.choice(len(df))
visualize(random_idx)

Text one: It’s been 1 year since the pandemic was declared. Join ANA on 3/11 to honor the 500+ #nurses who lost their lives to #COVID19 in the U.S. w/ a #DayofRe
membrance. We urge all to join in solidarity by wearing a white or blue ribbon, lighting a candle, or for a moment of silence. https://t.co/IWibx1s2x2
Label: NoEntailment

Text two: It’s been 1 year since the pandemic was declared. Join #ANA on 3/11 to honor the 500+ #nurses who lost their lives to #COVID19 in the U.S. w/ a #DayofR
emembrance. We urge all to join in solidarity by wearing a white or blue ribbon, lighting a candle, or for a moment of silence. https://t.co/dDbG3mNsuK
Label: Implies
df["label"].value_counts()
label
NoEntailment     1182
Implies           109
Contradictory     109
Name: count, dtype: int64

 

데이터셋 분리

 

# 20% for test
train_df, test_df = train_test_split(
    df, test_size=0.2, stratify=df["label"].values, random_state=42
)

# 20% for validation
train_df, val_df = train_test_split(
    train_df, test_size=0.25, stratify=train_df["label"].values, random_state=42
)

print(f"Total training examples: {len(train_df)}")
print(f"Total validation examples: {len(val_df)}")
print(f"Total test examples: {len(test_df)}")
Total training examples: 840
Total validation examples: 280
Total test examples: 280

 

728x90
반응형
LIST

'Python Library > Keras' 카테고리의 다른 글

[Keras] 모델 플롯 유틸리티  (0) 2024.04.02
[Keras] 멀티모달 함의 분류 (2)  (0) 2024.04.02
[Keras] ImageDataGenerator class weight  (0) 2023.09.08
[Keras] tflite 변환  (0) 2022.11.24
[Keras] ImageDataGenerator  (0) 2022.08.20