# Colab'da çalıştır
!wget -q https://download.microsoft.com/download/3/E/1/3E1C3F21-ECDB-4869-8368-6deba77b919f/kagglecatsanddogs_5340.zip
!unzip -q kagglecatsanddogs_5340.zip
!rm -rf PetImages/*/*.jpg* # Bozuk dosyaları temizle# Python
# 1. Kütüphaneler
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.applications import MobileNetV3Small
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D, Dropout
from tensorflow.keras.models import Model
import matplotlib.pyplot as plt
print(f"TensorFlow sürümü: {tf.__version__}")
print(f"GPU var mı? {tf.config.list_physical_devices('GPU')}")
# 2. Veri ön İşleme (Data Augmentation)
train_datagen = ImageDataGenerator(
rescale=1./255,
rotation_range=20,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
validation_split=0.2
)
train_generator = train_datagen.flow_from_directory(
'PetImages',
target_size=(224, 224),
batch_size=32,
class_mode='binary',
subset='training'
)
val_generator = train_datagen.flow_from_directory(
'PetImages',
target_size=(224, 224),
batch_size=32,
class_mode='binary',
subset='validation'
)
# 3. Transfer Learning - MobileNetV3 (2025 en hafif ve güçlü model)
base_model = MobileNetV3Small(
input_shape=(224, 224, 3),
include_top=False,
weights='imagenet'
)
base_model.trainable = False # Önce sadece üst katmanları eğit
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dropout(0.5)(x)
x = Dense(128, activation='relu')(x)
predictions = Dense(1, activation='sigmoid')(x)
model = Model(inputs=base_model.input, outputs=predictions)
model.compile(
optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy']
)
# 4. İlk Eğitim (10 epoch - Hızlı Öğrenme)
history = model.fit(
train_generator,
epochs=10,
validation_data=val_generator
)
# 5. Fine-Tuning (Daha Yüksek Doğruluk İçin)
base_model.trainable = True
# Sadece son 20 katmanı eğit
for layer in base_model.layers[:-20]:
layer.trainable = False
model.compile(
optimizer=tf.keras.optimizers.Adam(1e-5), # Çok düşük learning rate
loss='binary_crossentropy',
metrics=['accuracy']
)
history_fine = model.fit(
train_generator,
epochs=15,
validation_data=val_generator
)
# 6. Sonuç Grafiği
plt.figure(figsize=(12,4))
plt.subplot(1,2,1)
plt.plot(history_fine.history['accuracy'], label='Eğitim Doğruluğu')
plt.plot(history_fine.history['val_accuracy'], label='Doğrulama Doğruluğu')
plt.title('Model Doğruluğu (15 epoch sonra)')
plt.legend()
plt.subplot(1,2,2)
plt.plot(history_fine.history['loss'], label='Eğitim Kaybı')
plt.plot(history_fine.history['val_loss'], label='Doğrulama Kaybı')
plt.title('Model Kaybı')
plt.legend()
plt.show()
print(f"Son doğrulama doğruluk: {max(history_fine.history['val_accuracy']):.4}")# Modeli kaydet
model.save('kedi_kopek_model_2025.h5')
# Tek fotoğraf testi
import numpy as np
from tensorflow.keras.preprocessing import image
def tahmin_yap(yol):
img = image.load_img(yol, target_size=(224, 224))
img_array = image.img_to_array(img)
img_array = np.expand_dims(img_array, axis=0) / 255.0
tahmin = model.predict(img_array)[0][0]
if tahmin > 0.5:
print(f"KÖPEK olasılığı: {tahmin:.4f}")
else:
print(f"KEDİ olasılığı: {1-tahmin:.4f}")
# Örnek Kullanım
tahmin_yap("ornek_kopek.jpg")pip install tensorflowjs
tensorflowjs_converter --input_format=keras kedi_kopek_model_2025.h5 web_model