Upload creacion_modelo.py
Browse files- creacion_modelo.py +79 -0
creacion_modelo.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from tensorflow.keras.preprocessing import image
|
| 3 |
+
import numpy as np
|
| 4 |
+
from sklearn.model_selection import train_test_split
|
| 5 |
+
from tensorflow.keras.models import Sequential
|
| 6 |
+
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
|
| 7 |
+
from tensorflow.keras.optimizers import Adam
|
| 8 |
+
|
| 9 |
+
# Ruta donde est谩n las im谩genes
|
| 10 |
+
dataset_path = 'train' # Cambia esta ruta a tu directorio 'train'
|
| 11 |
+
|
| 12 |
+
# Funci贸n para cargar y etiquetar las im谩genes
|
| 13 |
+
def load_images(dataset_path):
|
| 14 |
+
images = []
|
| 15 |
+
labels = []
|
| 16 |
+
|
| 17 |
+
# Iterar sobre todos los archivos en el directorio 'train'
|
| 18 |
+
for filename in os.listdir(dataset_path):
|
| 19 |
+
img_path = os.path.join(dataset_path, filename)
|
| 20 |
+
|
| 21 |
+
# Verificar si el archivo es una imagen (y tiene extensi贸n .jpg, .jpeg, .png)
|
| 22 |
+
if filename.lower().endswith(('jpg', 'jpeg', 'png')):
|
| 23 |
+
# Cargar y redimensionar la imagen
|
| 24 |
+
img = image.load_img(img_path, target_size=(150, 150)) # Redimensionar a 150x150
|
| 25 |
+
img_array = image.img_to_array(img) / 255.0 # Normalizar la imagen (dividir entre 255)
|
| 26 |
+
images.append(img_array)
|
| 27 |
+
|
| 28 |
+
# Etiquetar seg煤n el nombre del archivo
|
| 29 |
+
if 'cat' in filename.lower():
|
| 30 |
+
labels.append(0) # Gato (0)
|
| 31 |
+
elif 'dog' in filename.lower():
|
| 32 |
+
labels.append(1) # Perro (1)
|
| 33 |
+
|
| 34 |
+
# Convertir las listas a arrays numpy
|
| 35 |
+
images = np.array(images)
|
| 36 |
+
labels = np.array(labels)
|
| 37 |
+
return images, labels
|
| 38 |
+
|
| 39 |
+
# Cargar las im谩genes y las etiquetas
|
| 40 |
+
images, labels = load_images(dataset_path)
|
| 41 |
+
|
| 42 |
+
# Dividir el dataset en entrenamiento y validaci贸n (80% entrenamiento, 20% validaci贸n)
|
| 43 |
+
X_train, X_val, y_train, y_val = train_test_split(images, labels, test_size=0.2, random_state=42)
|
| 44 |
+
|
| 45 |
+
# Verifica el tama帽o de los datos
|
| 46 |
+
print(f"Tama帽o del conjunto de entrenamiento: {X_train.shape}")
|
| 47 |
+
print(f"Tama帽o del conjunto de validaci贸n: {X_val.shape}")
|
| 48 |
+
|
| 49 |
+
# Crear el modelo CNN
|
| 50 |
+
model = Sequential([
|
| 51 |
+
# Capa convolucional 1
|
| 52 |
+
Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3)),
|
| 53 |
+
MaxPooling2D(2, 2),
|
| 54 |
+
|
| 55 |
+
# Capa convolucional 2
|
| 56 |
+
Conv2D(64, (3, 3), activation='relu'),
|
| 57 |
+
MaxPooling2D(2, 2),
|
| 58 |
+
|
| 59 |
+
# Capa convolucional 3
|
| 60 |
+
Conv2D(128, (3, 3), activation='relu'),
|
| 61 |
+
MaxPooling2D(2, 2),
|
| 62 |
+
|
| 63 |
+
# Aplanar las salidas para conectarlas a una capa densa
|
| 64 |
+
Flatten(),
|
| 65 |
+
|
| 66 |
+
# Capa densa (fully connected)
|
| 67 |
+
Dense(512, activation='relu'),
|
| 68 |
+
Dropout(0.5), # Dropout para evitar sobreajuste
|
| 69 |
+
Dense(1, activation='sigmoid') # Salida binaria: gato o perro
|
| 70 |
+
])
|
| 71 |
+
|
| 72 |
+
# Compilar el modelo
|
| 73 |
+
model.compile(optimizer=Adam(), loss='binary_crossentropy', metrics=['accuracy'])
|
| 74 |
+
|
| 75 |
+
# Entrenar el modelo
|
| 76 |
+
model.fit(X_train, y_train, epochs=10, batch_size=32, validation_data=(X_val, y_val))
|
| 77 |
+
|
| 78 |
+
# Guardar el modelo entrenado
|
| 79 |
+
model.save('dogs_vs_cats_cnn.h5')
|