| import os |
| from tensorflow.keras.preprocessing import image |
| import numpy as np |
| from sklearn.model_selection import train_test_split |
| from tensorflow.keras.models import Sequential |
| from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout |
| from tensorflow.keras.optimizers import Adam |
|
|
| dataset_path = 'train' |
|
|
| def load_images(dataset_path): |
| images = [] |
| labels = [] |
| |
| for filename in os.listdir(dataset_path): |
| img_path = os.path.join(dataset_path, filename) |
| |
| if filename.lower().endswith(('jpg', 'jpeg', 'png')): |
| img = image.load_img(img_path, target_size=(150, 150)) |
| img_array = image.img_to_array(img) / 255.0 |
| images.append(img_array) |
| |
| if 'cat' in filename.lower(): |
| labels.append(0) |
| elif 'dog' in filename.lower(): |
| labels.append(1) |
| |
| images = np.array(images) |
| labels = np.array(labels) |
| return images, labels |
|
|
| images, labels = load_images(dataset_path) |
|
|
| X_train, X_val, y_train, y_val = train_test_split(images, labels, test_size=0.2, random_state=42) |
|
|
| print(f"Tamaño del conjunto de entrenamiento: {X_train.shape}") |
| print(f"Tamaño del conjunto de validación: {X_val.shape}") |
|
|
| model = Sequential([ |
| Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3)), |
| MaxPooling2D(2, 2), |
|
|
| Conv2D(64, (3, 3), activation='relu'), |
| MaxPooling2D(2, 2), |
|
|
| Conv2D(128, (3, 3), activation='relu'), |
| MaxPooling2D(2, 2), |
|
|
| Flatten(), |
| |
| Dense(512, activation='relu'), |
| Dropout(0.5), |
| Dense(1, activation='sigmoid') |
| ]) |
|
|
| model.compile(optimizer=Adam(), loss='binary_crossentropy', metrics=['accuracy']) |
|
|
| model.fit(X_train, y_train, epochs=10, batch_size=32, validation_data=(X_val, y_val)) |
|
|
| model.save('dogs_vs_cats_cnn.h5') |
|
|