From 4d6165575bf0a5ea768ce99063d3c5abd02a5096 Mon Sep 17 00:00:00 2001 From: cta Date: Wed, 4 Nov 2026 11:06:12 -0600 Subject: [PATCH] =?UTF-8?q?A=C3=B1adir=20entrenamiento=5Fmemoria.py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- entrenamiento_memoria.py | 240 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 240 insertions(+) create mode 100644 entrenamiento_memoria.py diff --git a/entrenamiento_memoria.py b/entrenamiento_memoria.py new file mode 100644 index 0000000..76709d2 --- /dev/null +++ b/entrenamiento_memoria.py @@ -0,0 +1,240 @@ +import argparse +import os +import time +import csv + +import numpy as np +import psutil +import tensorflow as tf +import matplotlib.pyplot as plt + + +parser = argparse.ArgumentParser() + +parser.add_argument( + "--batch", + type=int, + required=True +) + +args = parser.parse_args() + +BATCH_SIZE = args.batch +EPOCHS = 5 + + +# ------------------------------------------------- +# Información del proceso +# ------------------------------------------------- + +process = psutil.Process(os.getpid()) + +print("=" * 60) +print("EXPERIMENTO DE MEMORIA - TENSORFLOW") +print("=" * 60) + +print("PID:", os.getpid()) +print("Batch size:", BATCH_SIZE) +print("CPU disponibles:", os.cpu_count()) + + +# ------------------------------------------------- +# Dataset sintético +# ------------------------------------------------- + +NUM_SAMPLES = 30000 +NUM_FEATURES = 256 +NUM_CLASSES = 10 + +print("\nGenerando dataset...") + +X = np.random.randn( + NUM_SAMPLES, + NUM_FEATURES +).astype("float32") + +y = np.random.randint( + 0, + NUM_CLASSES, + size=NUM_SAMPLES +).astype("int32") + + +# ------------------------------------------------- +# Modelo +# ------------------------------------------------- + +model = tf.keras.Sequential([ + + tf.keras.layers.Input( + shape=(NUM_FEATURES,) + ), + + tf.keras.layers.Dense( + 512, + activation="relu" + ), + + tf.keras.layers.Dense( + 256, + activation="relu" + ), + + tf.keras.layers.Dense( + 128, + activation="relu" + ), + + tf.keras.layers.Dense( + NUM_CLASSES, + activation="softmax" + ) + +]) + + +model.compile( + optimizer="adam", + loss="sparse_categorical_crossentropy", + metrics=["accuracy"] +) + + +# ------------------------------------------------- +# Callback para medir RAM +# ------------------------------------------------- + +class MemoryMonitor(tf.keras.callbacks.Callback): + + def __init__(self): + super().__init__() + self.memory = [] + self.times = [] + + def on_train_begin(self, logs=None): + self.start = time.time() + + def on_epoch_end(self, epoch, logs=None): + + ram_mb = ( + process.memory_info().rss + / 1024 + / 1024 + ) + + elapsed = time.time() - self.start + + self.memory.append(ram_mb) + self.times.append(elapsed) + + print( + f"\nÉpoca {epoch + 1}: " + f"RAM = {ram_mb:.2f} MB" + ) + + +monitor = MemoryMonitor() + + +# ------------------------------------------------- +# Entrenamiento +# ------------------------------------------------- + +inicio = time.time() + +model.fit( + X, + y, + batch_size=BATCH_SIZE, + epochs=EPOCHS, + callbacks=[monitor], + verbose=1 +) + +fin = time.time() + +total_time = fin - inicio + + +# ------------------------------------------------- +# Resultados +# ------------------------------------------------- + +peak_memory = max(monitor.memory) + +print("\n" + "=" * 60) +print("RESULTADOS") +print("=" * 60) + +print( + f"Batch size: {BATCH_SIZE}" +) + +print( + f"RAM máxima: {peak_memory:.2f} MB" +) + +print( + f"Tiempo: {total_time:.2f} segundos" +) + + +# ------------------------------------------------- +# Guardar CSV +# ------------------------------------------------- + +csv_name = f"memoria_batch_{BATCH_SIZE}.csv" + +with open( + csv_name, + "w", + newline="" +) as file: + + writer = csv.writer(file) + + writer.writerow([ + "epoch", + "memory_mb" + ]) + + for epoch, memory in enumerate( + monitor.memory, + start=1 + ): + + writer.writerow([ + epoch, + memory + ]) + + +# ------------------------------------------------- +# Gráfica +# ------------------------------------------------- + +plt.figure(figsize=(8, 5)) + +plt.plot( + range(1, EPOCHS + 1), + monitor.memory, + marker="o" +) + +plt.xlabel("Época") + +plt.ylabel("RAM del proceso (MB)") + +plt.title( + f"Uso de memoria - Batch {BATCH_SIZE}" +) + +plt.grid(True) + +plt.tight_layout() + +plt.savefig( + f"memoria_batch_{BATCH_SIZE}.png" +) + +print("\nGráfica generada.") \ No newline at end of file