Simple CNN Mobil vs Sepeda
contoh gambar kustom untuk melatih CNN
Simple CNN Mobil vs Sepeda
contoh gambar kustom untuk melatih CNN
Assalamu’alaikum teman-teman data
berikut disajikan koding untuk mencoba CNN dengan pelatihan data gambar sedikit, namun sebelumnya kita gunakan data image kumpulan dari CIFAR-10
Kita seting dulu environmentnya
import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.preprocessing.image import load_img, img_to_array
import numpy as np
import matplotlib.pyplot as plt
import os
# 1. Siapkan Dataset Kustom (Contoh: CIFAR-10)
# Jika pakai CIFAR-10, kelas 1 (mobil) dan 2 (sepeda)
(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.cifar10.load_data()
# Filter hanya kelas mobil (label 1) dan sepeda (label 2)
def filter_classes(images, labels, class1=1, class2=2):
mask = (labels == class1) | (labels == class2)
images = images[mask.squeeze()]
labels = labels[mask]
# Ubah label: mobil=0, sepeda=1
labels = np.where(labels == class1, 0, 1)
return images, labels
# Training data: 5 mobil + 5 sepeda
train_images, train_labels = filter_classes(train_images, train_labels)
train_images = train_images[:10] # Ambil 10 gambar (5 per kelas)
train_labels = train_labels[:10]
# Testing data: 3 mobil + 3 sepeda
test_images, test_labels = filter_classes(test_images, test_labels)
test_images = test_images[:6] # Ambil 6 gambar (3 per kelas)
test_labels = test_labels[:6]
# Normalisasi gambar
train_images = train_images.astype('float32') / 255
test_images = test_images.astype('float32') / 255
# 2. Bangun Model untuk Klasifikasi Biner
model = models.Sequential([
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Flatten(),
layers.Dense(64, activation='relu'),
layers.Dense(1, activation='sigmoid') # Output biner
])
model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
# 3. Latih Model
model.fit(train_images, train_labels, epochs=10, batch_size=2)
# 4. Evaluasi
test_loss, test_acc = model.evaluate(test_images, test_labels)
print(f"Akurasi Testing: {test_acc}")
# 5. Prediksi Gambar Baru
def predict_custom_image(image_path):
img = load_img(image_path, target_size=(32, 32))
img_array = img_to_array(img) / 255.0
img_array = np.expand_dims(img_array, axis=0)
prediction = model.predict(img_array)
class_name = "Mobil" if prediction < 0.5 else "Sepeda"
plt.imshow(img)
plt.title(f"Prediksi: {class_name} ({prediction[0][0]:.2f})")
plt.axis('off')
plt.show()
# Contoh prediksi gambar baru (ganti path-nya)
predict_custom_image("path/to/your/custom_image.jpg")
kemudian dapat anda coba untuk memprediksi salahsatu gambar yang anda inginkan, dan gantilah path file anda di baris perintah paling bawah tersebut. Bagaimana jika anda ingin memprediksikan gambar melalui data training sendiri? Nah siapkan data gambar anda (misal 5 gambar mobil dan 5 gambar sepeda untuk training) kemudian siapkan juga untuk data testing (3 gambar mobil dan 3 gambar sepeda) kemudian susunlah seperti berikut,
dataset/
train/
mobil/ # 5 gambar
sepeda/ # 5 gambar
test/
mobil/ # 3 gambar
sepeda/ # 3 gambar
kemudian gantilah koding pada bagian pengambilan datanya seperti berikut,
train_ds = tf.keras.preprocessing.image_dataset_from_directory(
'dataset/train', image_size=(32, 32), batch_size=10
)
test_ds = tf.keras.preprocessing.image_dataset_from_directory(
'dataset/test', image_size=(32, 32), batch_size=6
)
gantilah path tersebut dengan path yang anda buat untuk menyimpan data training dan testing.
Hasil akhir bisa seperti ini,

silahkan mencoba
메타데이터
- post_id
- 88ff28e71dbb
- slug
- simple-cnn-mobil-vs-sepeda-88ff28e71dbb
- url
- https://medium.com/@986110101/simple-cnn-mobil-vs-sepeda-88ff28e71dbb
- canonical_url
- https://medium.com/@986110101/simple-cnn-mobil-vs-sepeda-88ff28e71dbb
- author_url
- https://medium.com/@986110101
- status
- ok
- fetched_at
- 2026-07-20 02:06:23