신경망 기본 구조
입력 계층 → 은닉 계층(데이터 처리) → 출력 계층
- 입력 계층: 외부 정보 수신
- 은닉 계층: 다중 변환을 통한 특징 추출
- 출력 계층: 최종 결과 도출
각 계층은 특정 연산을 수행하며, 신경망은 입력 데이터를 계층적 변환을 통해 출력으로 매핑합니다.
데이터 흐름 그래프
TensorFlow는 데이터 흐름 그래프를 사용한 계산 프레임워크입니다.
- 노드: 수학적 연산(Operation)
- 에지: 다차원 데이터 배열(Tensor)

텐서는 그래프를 따라 이동하며 연산에 의해 변환됩니다. TensorFlow는 필요한 노드만 실행하는 지연 실행 방식을 사용합니다.
텐서 개념
TensorFlow에서 모든 데이터는 텐서로 표현됩니다.
| 차원 | 유형 | 예시 |
|---|---|---|
| 0D | 스칼라 | 5 |
| 1D | 벡터 | [1,2,3] |
| 2D | 행렬 | [[1,2],[3,4]] |
| 3D+ | 고차원 텐서 | 다차원 배열 |
선형 회귀 예제
import tensorflow as tf
import numpy as np
# 데이터 생성
x_input = np.random.rand(100).astype(np.float32)
y_true = x_input * 0.2 + 0.4
# 모델 구성
weight = tf.Variable(tf.random_uniform([1], -0.5, 0.5))
bias = tf.Variable(tf.zeros([1]))
y_pred = weight * x_input + bias
# 학습 설정
loss = tf.reduce_mean(tf.square(y_pred - y_true))
optimizer = tf.train.GradientDescentOptimizer(0.3)
train_op = optimizer.minimize(loss)
# 실행
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for epoch in range(201):
sess.run(train_op)
if epoch % 25 == 0:
w_val, b_val = sess.run([weight, bias])
print(f"Epoch {epoch}: Weight={w_val[0]:.4f}, Bias={b_val[0]:.4f}")
세션 제어 예제
import tensorflow as tf
# 행렬 연산 정의
mat_a = tf.constant([[4,4]])
mat_b = tf.constant([[3],[3]])
product = tf.matmul(mat_a, mat_b)
# 세션 실행
with tf.Session() as sess:
result = sess.run(product)
print("Matrix product:", result) # 출력: [[24]]
변수 관리 예제
import tensorflow as tf
counter = tf.Variable(10, name='count')
increment = tf.constant(2)
new_count = tf.add(counter, increment)
update = tf.assign(counter, new_count)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for _ in range(3):
sess.run(update)
current = sess.run(counter)
print("Current value:", current)
플레이스홀더 예제
import tensorflow as tf
a = tf.placeholder(tf.float32)
b = tf.placeholder(tf.float32)
mul_result = tf.multiply(a, b)
with tf.Session() as sess:
output = sess.run(mul_result, feed_dict={a: [7], b: [3]})
print("Multiplication result:", output) # 출력: [21.]
활성화 함수
신경망에서 비선형성을 도입하는 핵심 요소입니다.
- ReLU: 음수 영역을 0으로 처리
- Sigmoid: 출력을 [0,1] 범위로 압축
- Tanh: 출력을 [-1,1] 범위로 조정
계층별 권장 사항:
- CNN: ReLU 우선 적용
- RNN: Tanh 또는 ReLU 사용
- 깊은 신경망: 기울기 소실 문제 고려