-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrain.py
More file actions
72 lines (59 loc) · 2.12 KB
/
train.py
File metadata and controls
72 lines (59 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import os, json
import numpy as np
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.optimizers import RMSprop
print("TF:", tf.__version__)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DATA_DIR = os.path.join(BASE_DIR, "sample")
OUT_DIR = os.path.join(BASE_DIR, "artifacts")
os.makedirs(OUT_DIR, exist_ok=True)
MODEL_PATH = os.path.join(OUT_DIR, "model.keras")
CLASSES_PATH = os.path.join(OUT_DIR, "class_names.json")
IMG_SIZE = (200, 200)
BATCH_SIZE = 2
SEED = 42
# ✅ 데이터가 너무 적으니 일단 train에 전부 사용 (validation 없음)
train_gen = ImageDataGenerator(rescale=1.0 / 255.0)
train_ds = train_gen.flow_from_directory(
DATA_DIR,
target_size=IMG_SIZE,
batch_size=BATCH_SIZE,
class_mode="binary",
shuffle=True,
seed=SEED
)
# 클래스명 저장 (Streamlit에서 동일 매핑을 쓰기 위해 필수)
# 예: {'NG':0, 'OK':1} -> index 순서에 맞게 ["NG","OK"]
class_indices = train_ds.class_indices
class_names = [None] * len(class_indices)
for name, idx in class_indices.items():
class_names[idx] = name
print("class_indices:", class_indices)
print("class_names:", class_names)
with open(CLASSES_PATH, "w", encoding="utf-8") as f:
json.dump(class_names, f, ensure_ascii=False, indent=2)
# ✅ 모델
model = tf.keras.Sequential([
tf.keras.layers.Input(shape=(IMG_SIZE[0], IMG_SIZE[1], 3)),
tf.keras.layers.Conv2D(16, (3,3), activation="relu"),
tf.keras.layers.MaxPool2D(2,2),
tf.keras.layers.Conv2D(32, (3,3), activation="relu"),
tf.keras.layers.MaxPool2D(2,2),
tf.keras.layers.Conv2D(64, (3,3), activation="relu"),
tf.keras.layers.MaxPool2D(2,2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation="relu"),
tf.keras.layers.Dropout(0.3),
tf.keras.layers.Dense(1, activation="sigmoid")
])
model.compile(
loss="binary_crossentropy",
optimizer=RMSprop(learning_rate=0.001),
metrics=["accuracy"]
)
history = model.fit(train_ds, epochs=30)
# ✅ 저장
model.save(MODEL_PATH)
print("\nSaved model to:", MODEL_PATH)
print("Saved classes to:", CLASSES_PATH)