[code] tensorflow.keras κ²½μ‚¬ν•˜κ°•λ²• μ΅œμ ν™” μ½”λ“œ

μˆ˜μ • λͺ©λ‘



## 첫번째 μ…€
import tensorflow as tf

## λ‘λ²ˆμ§Έ μ…€
print(tf.__version__)

## μ„Έλ²ˆμ§Έ μ…€ (μœ„ μ…€μ—μ„œ 버전이 2.15.0이 μ•„λ‹ˆλ©΄ ν˜„μž¬μ˜ ν…μ„œν”Œλ‘œμš°λ₯Ό μ•„λž˜μ™€ 같이 μ‚­μ œ)
!pip uninstall tensorflow

## λ„€λ²ˆμ§Έ μ…€ - μ‚­μ œκ°€ μ™„λ£Œλ˜λ©΄ μ•„λž˜μ™€ 같이 2.15.0 버전을 μž¬μ„€μΉ˜
!pip install tensorflow==2.15.0

## λ‹€μ„―λ²ˆμ§Έ μ…€ - λ‹€μ‹œ 버전 확인
print(tf.__version__)

## μ—¬μ„―λ²ˆμ§Έ μ…€

# 데이터 μ •μ˜
height = tf.constant([170, 180, 175, 160], dtype=tf.float32)
foot_size = tf.constant([260, 270, 265, 255], dtype=tf.float32)

# λ³€μˆ˜ μ •μ˜
a = tf.Variable(0.1) # μ΄ˆκΈ°κ°’ 0.1
b = tf.Variable(0.2) # μ΄ˆκΈ°κ°’ 0.2

# 손싀 ν•¨μˆ˜ μ •μ˜
def loss_func():
loss = tf.constant(0.0, dtype=tf.float32) # loss μ΄ˆκΈ°ν™”
for i in range(len(height)):
predicted = height[i] * a + b # 예츑 κ°’
loss += tf.square(foot_size[i] - predicted) # 손싀 계산
return loss

# κ²½μ‚¬ν•˜κ°•λ²• μ΅œμ ν™”
opt = tf.keras.optimizers.Adam(learning_rate=0.1)

# ν•™μŠ΅ 루프
for i in range(100):
opt.minimize(loss_func, var_list=[a, b]) # 손싀 ν•¨μˆ˜ μ΅œμ†Œν™”
print(f"Step {i + 1}, a: {a.numpy()}, b: {b.numpy()}")