Spaces:
Runtime error
Runtime error
Create file train_model.py
Browse files- train_model.py +55 -0
train_model.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import tensorflow as tf
|
| 2 |
+
import numpy as np
|
| 3 |
+
from datasets import load_dataset
|
| 4 |
+
from sklearn.preprocessing import LabelBinarizer
|
| 5 |
+
from tensorflow.keras.applications import MobileNetV2
|
| 6 |
+
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D
|
| 7 |
+
from tensorflow.keras.models import Model
|
| 8 |
+
from tensorflow.keras.optimizers import Adam
|
| 9 |
+
from tqdm import tqdm
|
| 10 |
+
|
| 11 |
+
# Load dataset dari Hugging Face
|
| 12 |
+
dataset = load_dataset("tanganke/stanford_cars")
|
| 13 |
+
NUM_CLASSES = 196
|
| 14 |
+
IMG_SIZE = 224
|
| 15 |
+
BATCH_SIZE = 32
|
| 16 |
+
EPOCHS = 5
|
| 17 |
+
|
| 18 |
+
# Preprocessing fungsi
|
| 19 |
+
def preprocess(example):
|
| 20 |
+
image = example["image"].resize((IMG_SIZE, IMG_SIZE))
|
| 21 |
+
image = np.array(image) / 255.0
|
| 22 |
+
return image, example["label"]
|
| 23 |
+
|
| 24 |
+
# Apply preprocessing
|
| 25 |
+
X_train, y_train = zip(*[preprocess(x) for x in tqdm(dataset["train"])])
|
| 26 |
+
X_test, y_test = zip(*[preprocess(x) for x in tqdm(dataset["test"])])
|
| 27 |
+
|
| 28 |
+
X_train = np.array(X_train)
|
| 29 |
+
X_test = np.array(X_test)
|
| 30 |
+
|
| 31 |
+
# One-hot encoding label
|
| 32 |
+
lb = LabelBinarizer()
|
| 33 |
+
y_train = lb.fit_transform(y_train)
|
| 34 |
+
y_test = lb.transform(y_test)
|
| 35 |
+
|
| 36 |
+
# Load base model MobileNetV2
|
| 37 |
+
base_model = MobileNetV2(include_top=False, input_shape=(IMG_SIZE, IMG_SIZE, 3), weights='imagenet')
|
| 38 |
+
x = GlobalAveragePooling2D()(base_model.output)
|
| 39 |
+
x = Dense(256, activation='relu')(x)
|
| 40 |
+
preds = Dense(NUM_CLASSES, activation='softmax')(x)
|
| 41 |
+
|
| 42 |
+
model = Model(inputs=base_model.input, outputs=preds)
|
| 43 |
+
|
| 44 |
+
# Freeze base layers
|
| 45 |
+
for layer in base_model.layers:
|
| 46 |
+
layer.trainable = False
|
| 47 |
+
|
| 48 |
+
model.compile(optimizer=Adam(1e-4), loss='categorical_crossentropy', metrics=['accuracy'])
|
| 49 |
+
|
| 50 |
+
# Training
|
| 51 |
+
model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=EPOCHS, batch_size=BATCH_SIZE)
|
| 52 |
+
|
| 53 |
+
# Simpan model
|
| 54 |
+
model.save("model/car_model.h5")
|
| 55 |
+
print("✅ Model saved to model/car_model.h5")
|