Keras 를 사용해서 몸무게, 나이 데이터를 가지고 혈중지방을 예측하는 모델을 만들어보기
In [1]:
# Blood Fat 데이터를 NumPy 배열로 변환
import numpy as np
# 원본 데이터 (Weight, Age, Blood fat content)
data = np.array([
[84, 46, 354],
[73, 20, 190],
[65, 52, 405],
[70, 30, 263],
[76, 57, 451],
[69, 25, 302],
[63, 28, 288],
[72, 36, 385],
[79, 57, 402],
[75, 44, 365],
[27, 24, 209],
[89, 31, 290],
[65, 52, 346],
[57, 23, 254],
[59, 60, 395],
[69, 48, 434],
[60, 34, 220],
[79, 51, 374],
[75, 50, 308],
[82, 34, 220],
[59, 46, 311],
[67, 23, 181],
[85, 37, 274],
[55, 40, 303],
[63, 30, 244]
])In [2]:
import matplotlib.pyplot as plt
xs = np.array(data[:,0], dtype=np.float32)
ys = np.array(data[:,1], dtype=np.float32)
zs = np.array(data[:,2], dtype=np.float32)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(xs, ys, zs)
ax.set_xlabel('Weight')
ax.set_ylabel('Age')
ax.set_zlabel('Blood fat')
plt.show()In [3]:
X = np.array(data[:, 0:2])
y = np.array(data[:, 2:])
y = y.reshape(-1, 1)
print(X.shape, y.shape)(25, 2) (25, 1)
In [12]:
import tensorflow as tf
model = tf.keras.Sequential([
tf.keras.layers.Input(shape=(2,)),
tf.keras.layers.Dense(1)
])
model.compile(optimizer="rmsprop", loss="mse")
model.summary()Model: "sequential_1"
Plain text view
[1mModel: "sequential_1"[0m
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓ ┃ Layer (type) ┃ Output Shape ┃ Param # ┃ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩ │ dense_1 (Dense) │ (None, 1) │ 3 │ └─────────────────────────────────┴────────────────────────┴───────────────┘
Plain text view
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓ ┃[1m [0m[1mLayer (type) [0m[1m [0m┃[1m [0m[1mOutput Shape [0m[1m [0m┃[1m [0m[1m Param #[0m[1m [0m┃ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩ │ dense_1 ([38;5;33mDense[0m) │ ([38;5;45mNone[0m, [38;5;34m1[0m) │ [38;5;34m3[0m │ └─────────────────────────────────┴────────────────────────┴───────────────┘
Total params: 3 (12.00 B)
Plain text view
[1m Total params: [0m[38;5;34m3[0m (12.00 B)
Trainable params: 3 (12.00 B)
Plain text view
[1m Trainable params: [0m[38;5;34m3[0m (12.00 B)
Non-trainable params: 0 (0.00 B)
Plain text view
[1m Non-trainable params: [0m[38;5;34m0[0m (0.00 B)
모델 학습
나이와 몸무게를 이용해 blood fat 을 추정하는 모델을 훈련
In [5]:
hist = model.fit(X, y, epochs=10000, verbose=0)2026-01-03 20:14:54.124083: I tensorflow/core/grappler/optimizers/custom_graph_optimizer_registry.cc:117] Plugin optimizer for device_type GPU is enabled.
In [6]:
import matplotlib.pyplot as plt
plt.plot(hist.history['loss'])
plt.title('Model loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.show()예측
몸무게와 나이를 주고 혈중지방을 예측해보기
In [7]:
model.predict(np.array([100, 44]).reshape(1, 2), verbose=0)array([[373.1172]], dtype=float32)
In [8]:
model.predict(np.array([60, 25]).reshape(1, 2), verbose=0)array([[220.09103]], dtype=float32)
훈련된 가중치와 bias 를 얻고 싶다면?
In [9]:
W_, b_ = model.get_weights()
print("Weight is", W_)
print("Bias is", b_)Weight is [[1.1913167] [5.5459733]] Bias is [9.962692]
In [10]:
x = np.linspace(20, 100, 50).reshape(50, 1)
y = np.linspace(10, 70, 50).reshape(50, 1)
X = np.concatenate((x, y), axis=1)
Z = np.matmul(X, W_) + b_In [11]:
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(xs, ys, zs)
ax.scatter(x, y, Z, color='r')
ax.set_xlabel('Weight')
ax.set_ylabel('Age')
ax.set_zlabel('Blood fat')
plt.show()