본문 바로가기
Tensorflow/RNN

python tensorflow rnn 코드 리뷰, 설명 꿀 팁

by 설화님 2024. 5. 13.

안녕하세요. 고명국입니다.

 

Rnn을 공부중인데, 아직 초기 단계라서,, 자세히 공부해 보려고 합니다.

약간,,, 고달프지만 :) 해야죠! 개발해야 하는데! pdm 포에버

 

 

import numpy as np

import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, LSTM, Dense, Concatenate
import matplotlib.pyplot as plt

# 데이터 생성 (임의의 예시 데이터)
num_samples = 1000
timesteps = 10
input_dim1 = 5
input_dim2 = 3

# 랜덤 데이터 생성
data1 = np.random.random((num_samples, timesteps, input_dim1))
data2 = np.random.random((num_samples, timesteps, input_dim2))
labels = np.random.randint(2, size=(num_samples, 1))

# 모델 정의
input1 = Input(shape=(timesteps, input_dim1))
input2 = Input(shape=(timesteps, input_dim2))

# 첫 번째 입력에 대해 LSTM 적용
x1 = LSTM(32)(input1)

# 두 번째 입력에 대해 LSTM 적용
x2 = LSTM(32)(input2)

# 두 출력을 결합r
combined = Concatenate()([x1, x2])

# 결합된 출력을 Dense 레이어에 전달하여 최종 출력 계산
output = Dense(1, activation='sigmoid')(combined)

# 모델 생성 및 컴파일
model = Model(inputs=[input1, input2], outputs=output)
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

# 모델 요약 출력
model.summary()

# 모델 훈련
history = model.fit([data1, data2], labels, epochs=10, batch_size=32, validation_split=0.2)

# 훈련 결과를 그래프로 출력
plt.plot(history.history['loss'], label='Training Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.title('Model Loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()

plt.plot(history.history['accuracy'], label='Training Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.title('Model Accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()
plt.show()

 

 

 

코드 작성 순서. 

  1. 임의의 입력 데이터와 레이블을 생성합니다.
  2. 두 개의 입력을 받는 모델을 정의합니다.
  3. 각각의 입력에 대해 LSTM 레이어를 적용합니다.
  4. 두 개의 LSTM 출력을 결합합니다.
  5. 결합된 출력을 Dense 레이어에 전달하여 최종 출력을 계산합니다.
  6. 모델을 컴파일하고 훈련합니다.
  7. 훈련 결과를 그래프로 출력합니다