diff --git a/.github/workflows/python-publish.yml b/.github/workflows/python-publish.yml new file mode 100644 index 0000000..bdaab28 --- /dev/null +++ b/.github/workflows/python-publish.yml @@ -0,0 +1,39 @@ +# This workflow will upload a Python Package using Twine when a release is created +# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python#publishing-to-package-registries + +# This workflow uses actions that are not certified by GitHub. +# They are provided by a third-party and are governed by +# separate terms of service, privacy policy, and support +# documentation. + +name: Upload Python Package + +on: + release: + types: [published] + +permissions: + contents: read + +jobs: + deploy: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - name: Set up Python + uses: actions/setup-python@v3 + with: + python-version: '3.x' + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install build + - name: Build package + run: python -m build + - name: Publish package + uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29 + with: + user: __token__ + password: ${{ secrets.PYPI_API_TOKEN }} diff --git a/PROGRAMAS DE PYTHON/ASCIIArtGeneratorinPython.py b/PROGRAMAS DE PYTHON/ASCIIArtGeneratorinPython.py new file mode 100644 index 0000000..ed8a5c3 --- /dev/null +++ b/PROGRAMAS DE PYTHON/ASCIIArtGeneratorinPython.py @@ -0,0 +1,57 @@ +from PIL import Image + +# Definimos una lista de caracteres ASCII que utilizaremos para el arte +ASCII_CHARS = ["@", "#", "S", "%", "?", "*", "+", ";", ":", ",", "."] + +# Cambia el tamaño de la imagen +def resize_image(image, new_width=100): + width, height = image.size + ratio = height / width + new_height = int(new_width * ratio) + resized_image = image.resize((new_width, new_height)) + return resized_image + +# Convierte la imagen a escala de grises +def grayify(image): + grayscale_image = image.convert("L") + return grayscale_image + +# Convierte cada píxel a un carácter ASCII +def pixels_to_ascii(image): + pixels = image.getdata() + ascii_str = "" + for pixel in pixels: + ascii_str += ASCII_CHARS[pixel // 25] + return ascii_str + +# Función principal para convertir una imagen a arte ASCII +def image_to_ascii(image_path, new_width=100): + try: + image = Image.open(image_path) + except Exception as e: + print(f"Unable to open image file {image_path}. {e}") + return + + image = resize_image(image, new_width) + image = grayify(image) + + ascii_str = pixels_to_ascii(image) + img_width = image.width + ascii_str_len = len(ascii_str) + ascii_img = "" + + # Dividir el string de caracteres ASCII en líneas para que se ajuste al ancho de la imagen + for i in range(0, ascii_str_len, img_width): + ascii_img += ascii_str[i:i+img_width] + "\n" + + return ascii_img + +# Función para mostrar el arte ASCII en la consola +def main(): + image_path = input("Enter the path to the image file: ") + ascii_art = image_to_ascii(image_path) + if ascii_art: + print(ascii_art) + +if __name__ == "__main__": + main() diff --git a/PROGRAMAS DE PYTHON/Automata1.py b/PROGRAMAS DE PYTHON/Automata1.py new file mode 100644 index 0000000..179eb66 --- /dev/null +++ b/PROGRAMAS DE PYTHON/Automata1.py @@ -0,0 +1,40 @@ +automata = { + 'estados': {'q0', 'q1', 'q2', 'q3', 'q4'}, + 'alfabeto': {'0', '1'}, + 'estado_inicial': 'q0', + 'estados_aceptacion': {'q3', 'q4'}, + 'transiciones': { + ('q0', '0'): 'q1', + ('q0', '1'): 'q2', + ('q1', '0'): 'q3', + ('q1', '1'): 'q2', + ('q2', '0'): 'q2', + ('q2', '1'): 'q4', + ('q3', '0'): 'q3', + ('q3', '1'): 'q4', + ('q4', '0'): 'q4', + ('q4', '1'): 'q4' + } +} + +def simular_automata(automata, cadena): + estado_actual = automata['estado_inicial'] + for simbolo in cadena: + if (estado_actual, simbolo) in automata['transiciones']: + estado_actual = automata['transiciones'][(estado_actual, simbolo)] + else: + return False + return estado_actual in automata['estados_aceptacion'] + +cadena1 = '0011' +cadena2 = '0110' + +if simular_automata(automata, cadena1): + print(f'La cadena "{cadena1}" es aceptada por el autómata.') +else: + print(f'La cadena "{cadena1}" no es aceptada por el autómata.') + +if simular_automata(automata, cadena2): + print(f'La cadena "{cadena2}" es aceptada por el autómata.') +else: + print(f'La cadena "{cadena2}" no es aceptada por el autómata.') diff --git a/PROGRAMAS DE PYTHON/Automata2.py b/PROGRAMAS DE PYTHON/Automata2.py new file mode 100644 index 0000000..95e4656 --- /dev/null +++ b/PROGRAMAS DE PYTHON/Automata2.py @@ -0,0 +1,35 @@ +automata = { + 'estados': {'q0', 'q1', 'q2', 'q3', 'q4'}, + 'alfabeto': {'0', '1'}, + 'estado_inicial': 'q0', + 'estados_aceptacion': {'q3', 'q4'}, + 'transiciones': { + ('q0', '0'): 'q1', + ('q0', '1'): 'q2', + ('q1', '0'): 'q3', + ('q1', '1'): 'q2', + ('q2', '0'): 'q2', + ('q2', '1'): 'q4', + ('q3', '0'): 'q3', + ('q3', '1'): 'q4', + ('q4', '0'): 'q4', + ('q4', '1'): 'q4' + } +} + +def simular_automata(automata, cadena): + estado_actual = automata['estado_inicial'] + for simbolo in cadena: + if (estado_actual, simbolo) in automata['transiciones']: + estado_actual = automata['transiciones'][(estado_actual, simbolo)] + else: + return False + return estado_actual in automata['estados_aceptacion'] + +cadena = input("Ingrese una cadena: ") + +if simular_automata(automata, cadena): + print(f'La cadena "{cadena}" es aceptada por el autómata.') +else: + print(f'La cadena "{cadena}" no es aceptada por el autómata.') + diff --git a/PROGRAMAS DE PYTHON/Funcion.py b/PROGRAMAS DE PYTHON/Funcion.py new file mode 100644 index 0000000..a2e693a --- /dev/null +++ b/PROGRAMAS DE PYTHON/Funcion.py @@ -0,0 +1,7 @@ +def saludar_persona(): + nombre = input("Por favor, ingresa tu nombre: ") + mensaje = f"Hola, {nombre}! ¡Bienvenido!" + return mensaje + +saludo = saludar_persona() +print(saludo) diff --git a/PROGRAMAS DE PYTHON/Hash.py b/PROGRAMAS DE PYTHON/Hash.py new file mode 100644 index 0000000..1c48b46 --- /dev/null +++ b/PROGRAMAS DE PYTHON/Hash.py @@ -0,0 +1,98 @@ +class HashNode: + def __init__(self, key, value): + self.key = key + self.value = value + self.deleted = False + +class HashTable: + def __init__(self, initial_size=16): + self.size = initial_size + self.table = [None] * self.size + self.used_slots = 0 + self.deleted_slots = 0 + self.load_factor = 0.5 + self._resize_threshold = int(self.size * self.load_factor) + + def _hash_function(self, key): + return hash(key) % self.size + + def _double_hash(self, key, attempt): + return (self._hash_function(key) + attempt * (1 + hash(key) % (self.size - 1))) % self.size + + def _resize_table(self): + self.size *= 2 + new_table = [None] * self.size + + for node in filter(None, self.table): + index = self._find_empty_slot(new_table, node.key) + new_table[index] = node + + self.table = new_table + self._resize_threshold = int(self.size * self.load_factor) + + def _find_empty_slot(self, table, key): + attempt = 0 + index = self._double_hash(key, attempt) + while table[index] is not None and not table[index].deleted: + print(f"Collision at index {index} for key {key}. Trying next index.") + attempt += 1 + index = self._double_hash(key, attempt) + return index + + def insert(self, key, value): + if self.used_slots + self.deleted_slots >= self._resize_threshold: + print(f"Resizing table (current size: {self.size}).") + self._resize_table() + + attempt = 0 + index = self._find_empty_slot(self.table, key) + + if self.table[index] is None or self.table[index].deleted: + print(f"Inserting key {key} at index {index}.") + self.table[index] = HashNode(key, value) + self.used_slots += 1 + else: + print(f"Updating value for key {key} at index {index}.") + self.table[index].value = value + + def search(self, key): + attempt = 0 + index = self._double_hash(key, attempt) + + while self.table[index] is not None: + if not self.table[index].deleted and self.table[index].key == key: + print(f"Key {key} found at index {index}.") + return self.table[index].value + attempt += 1 + index = self._double_hash(key, attempt) + + raise KeyError(f"Key not found: {key}") + + def delete(self, key): + attempt = 0 + index = self._double_hash(key, attempt) + + while self.table[index] is not None: + if not self.table[index].deleted and self.table[index].key == key: + print(f"Deleting key {key} at index {index}.") + self.table[index].deleted = True + self.deleted_slots += 1 + self.used_slots -= 1 + return + attempt += 1 + index = self._double_hash(key, attempt) + + raise KeyError(f"Key not found: {key}") + +# Ejemplo de uso +hash_table = HashTable() +for i in range(1000): + hash_table.insert(f"key_{i}", f"value_{i}") + +print(hash_table.search("key_42")) + +hash_table.delete("key_42") +try: + print(hash_table.search("key_42")) +except KeyError as e: + print(e) diff --git a/PROGRAMAS DE PYTHON/IPTables1.py b/PROGRAMAS DE PYTHON/IPTables1.py new file mode 100644 index 0000000..741fd67 --- /dev/null +++ b/PROGRAMAS DE PYTHON/IPTables1.py @@ -0,0 +1,17 @@ +import subprocess + +# Función para agregar una regla al firewall IPTables +def agregar_regla(accion, protocolo, puerto): + comando = f"iptables -A INPUT -p {protocolo} --dport {puerto} -j {accion}" + subprocess.run(comando, shell=True) + +# Función para eliminar una regla del firewall IPTables +def eliminar_regla(accion, protocolo, puerto): + comando = f"iptables -D INPUT -p {protocolo} --dport {puerto} -j {accion}" + subprocess.run(comando, shell=True) + +# Agregar una regla para permitir conexiones TCP en el puerto 80 (HTTP) +agregar_regla("ACCEPT", "tcp", 80) + +# Eliminar la regla anterior +eliminar_regla("ACCEPT", "tcp", 80) diff --git a/PROGRAMAS DE PYTHON/IPTables2.py b/PROGRAMAS DE PYTHON/IPTables2.py new file mode 100644 index 0000000..6781791 --- /dev/null +++ b/PROGRAMAS DE PYTHON/IPTables2.py @@ -0,0 +1,7 @@ +import subprocess + +def permitir_ssh(): + comando = "iptables -A INPUT -p tcp --dport 22 -j ACCEPT" + subprocess.run(comando, shell=True) + +permitir_ssh() diff --git a/PROGRAMAS DE PYTHON/IPTables3.py b/PROGRAMAS DE PYTHON/IPTables3.py new file mode 100644 index 0000000..cd11313 --- /dev/null +++ b/PROGRAMAS DE PYTHON/IPTables3.py @@ -0,0 +1,8 @@ +import subprocess + +def establecer_regla_personalizada(ip_origen, ip_destino, puerto, accion): + comando = f"iptables -A INPUT -s {ip_origen} -d {ip_destino} -p tcp --dport {puerto} -j {accion}" + subprocess.run(comando, shell=True) + +establecer_regla_personalizada("192.168.1.100", "192.168.1.200", 22, "ACCEPT") + diff --git a/PROGRAMAS DE PYTHON/Lista.py b/PROGRAMAS DE PYTHON/Lista.py new file mode 100644 index 0000000..9b58cfa --- /dev/null +++ b/PROGRAMAS DE PYTHON/Lista.py @@ -0,0 +1,24 @@ +# Crear una lista vacía para almacenar la asistencia +asistencia = [] + +while True: + # Solicitar al usuario que ingrese el nombre del estudiante o 'q' para salir + nombre = input("Ingresa el nombre del estudiante (o 'q' para salir): ") + + if nombre.lower() == 'q': + break # Salir del bucle si se ingresa 'q' + + # Agregar el nombre del estudiante a la lista de asistencia + asistencia.append(nombre) + +# Mostrar la lista de asistencia +print("Lista de Asistencia:") +for estudiante in asistencia: + print(estudiante) + +# Guardar la lista de asistencia en un archivo de texto +with open("asistencia.txt", "w") as archivo: + for estudiante in asistencia: + archivo.write(estudiante + "\n") + +print("La lista de asistencia se ha guardado en 'asistencia.txt'.") diff --git a/PROGRAMAS DE PYTHON/ML1.py b/PROGRAMAS DE PYTHON/ML1.py new file mode 100644 index 0000000..fdf6b7b --- /dev/null +++ b/PROGRAMAS DE PYTHON/ML1.py @@ -0,0 +1,31 @@ +# Paso 1: Preparación de los Datos +import pandas as pd +from sklearn.model_selection import train_test_split + +# Cargar datos +data = pd.read_csv("datos_transacciones.csv") + +# Dividir datos en entrenamiento y prueba +X = data.drop("fraude", axis=1) # Características +y = data["fraude"] # Etiquetas +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) + +# Paso 2: Entrenamiento del Modelo +from sklearn.ensemble import RandomForestClassifier + +# Crear y entrenar el modelo +model = RandomForestClassifier() +model.fit(X_train, y_train) + +# Paso 3: Evaluación del Modelo +from sklearn.metrics import classification_report, confusion_matrix + +# Evaluar el modelo +y_pred = model.predict(X_test) +print("Matriz de Confusión:") +print(confusion_matrix(y_test, y_pred)) +print("Reporte de Clasificación:") +print(classification_report(y_test, y_pred)) + +# Paso 4: Implementación del Modelo +# Ahora puedes usar "model" para predecir fraudes en nuevas transacciones diff --git a/PROGRAMAS DE PYTHON/Monitor de Red en Tiempo Real.py b/PROGRAMAS DE PYTHON/Monitor de Red en Tiempo Real.py new file mode 100644 index 0000000..50360bb --- /dev/null +++ b/PROGRAMAS DE PYTHON/Monitor de Red en Tiempo Real.py @@ -0,0 +1,26 @@ +from scapy.all import sniff, IP, TCP, UDP + +# Función de callback para manejar los paquetes capturados +def packet_callback(packet): + # Si el paquete tiene una capa IP + if IP in packet: + ip_src = packet[IP].src + ip_dst = packet[IP].dst + + # Si el paquete tiene una capa TCP + if TCP in packet: + tcp_sport = packet[TCP].sport + tcp_dport = packet[TCP].dport + print(f"TCP Packet: {ip_src}:{tcp_sport} -> {ip_dst}:{tcp_dport}") + + # Si el paquete tiene una capa UDP + elif UDP in packet: + udp_sport = packet[UDP].sport + udp_dport = packet[UDP].dport + print(f"UDP Packet: {ip_src}:{udp_sport} -> {ip_dst}:{udp_dport}") + + else: + print(f"Other IP Packet: {ip_src} -> {ip_dst}") + +# Captura paquetes en la interfaz especificada (puedes cambiar 'eth0' por la interfaz de tu red) +sniff(prn=packet_callback, filter="ip", iface="eth0", store=0) diff --git a/PROGRAMAS DE PYTHON/Pandas1.py b/PROGRAMAS DE PYTHON/Pandas1.py new file mode 100644 index 0000000..027ab5c --- /dev/null +++ b/PROGRAMAS DE PYTHON/Pandas1.py @@ -0,0 +1,13 @@ +import pandas as pd + +# Cargar datos desde un archivo CSV +data = pd.read_csv("datos.csv") + +# Mostrar las primeras filas del DataFrame +print(data.head()) + +# Resumen estadístico del DataFrame +print(data.describe()) + +# Información sobre el DataFrame +print(data.info()) diff --git a/PROGRAMAS DE PYTHON/Red_neuronal_aprendizaje.py b/PROGRAMAS DE PYTHON/Red_neuronal_aprendizaje.py new file mode 100644 index 0000000..cf12b90 --- /dev/null +++ b/PROGRAMAS DE PYTHON/Red_neuronal_aprendizaje.py @@ -0,0 +1,44 @@ +import tensorflow as tf +from tensorflow.keras import layers, models +import matplotlib.pyplot as plt + +# Cargar el dataset de MNIST +(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data() + +# Normalizar las imágenes +train_images = train_images / 255.0 +test_images = test_images / 255.0 + +# Construir el modelo +model = models.Sequential([ + layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)), + layers.MaxPooling2D((2, 2)), + layers.Conv2D(64, (3, 3), activation='relu'), + layers.MaxPooling2D((2, 2)), + layers.Conv2D(64, (3, 3), activation='relu'), + layers.Flatten(), + layers.Dense(64, activation='relu'), + layers.Dense(10, activation='softmax') +]) + +# Compilar el modelo +model.compile(optimizer='adam', + loss='sparse_categorical_crossentropy', + metrics=['accuracy']) + +# Entrenar el modelo +history = model.fit(train_images, train_labels, epochs=5, + validation_data=(test_images, test_labels)) + +# Evaluar el modelo +test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2) +print(f'\nTest accuracy: {test_acc}') + +# Graficar el rendimiento del entrenamiento y la validación +plt.plot(history.history['accuracy'], label='accuracy') +plt.plot(history.history['val_accuracy'], label = 'val_accuracy') +plt.xlabel('Epoch') +plt.ylabel('Accuracy') +plt.ylim([0.8, 1]) +plt.legend(loc='lower right') +plt.show() diff --git a/PROGRAMAS DE PYTHON/SimulationofBruteForceAttack.py b/PROGRAMAS DE PYTHON/SimulationofBruteForceAttack.py new file mode 100644 index 0000000..023bd4e --- /dev/null +++ b/PROGRAMAS DE PYTHON/SimulationofBruteForceAttack.py @@ -0,0 +1,43 @@ +import itertools +import string +import time +import sys + +def brute_force_attack(password, charset, time_limit=1200): + start_time = time.time() + attempts = 0 + max_combinations = sum(len(charset) ** length for length in range(1, len(password) + 1)) + + for length in range(1, len(password) + 1): + for guess in itertools.product(charset, repeat=length): + if time.time() - start_time > time_limit: + print("\nTime limit exceeded. Attack interrupted.") + return None + + attempts += 1 + guess = ''.join(guess) + progress = attempts / max_combinations * 100 + sys.stdout.write(f"\rProgress: [{int(progress)}%] {guess}") + sys.stdout.flush() + + if guess == password: + end_time = time.time() + return (guess, attempts, end_time - start_time) + + return None + +def main(): + password = input("Enter the password to test: ") + charset = string.ascii_letters + string.digits + string.punctuation + + print(f"Starting brute force attack on password: {password}") + result = brute_force_attack(password, charset) + + if result: + guess, attempts, duration = result + print(f"\nPassword '{password}' cracked in {attempts} attempts and {duration:.2f} seconds.") + else: + print("\nFailed to crack the password.") + +if __name__ == "__main__": + main() diff --git a/PROGRAMAS DE PYTHON/antifraudes.py b/PROGRAMAS DE PYTHON/antifraudes.py new file mode 100644 index 0000000..350604c --- /dev/null +++ b/PROGRAMAS DE PYTHON/antifraudes.py @@ -0,0 +1,41 @@ +import pandas as pd +import numpy as np +from sklearn.model_selection import train_test_split +from sklearn.preprocessing import StandardScaler +from sklearn.ensemble import RandomForestClassifier +from sklearn.metrics import classification_report, confusion_matrix + +# Cargar datos +data = pd.read_csv('creditcard.csv') + +# Exploración básica de datos +print(data.head()) +print(data.info()) +print(data['Class'].value_counts()) + +# Separar características y la variable objetivo +X = data.drop('Class', axis=1) +y = data['Class'] + +# Dividir los datos en conjuntos de entrenamiento y prueba +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) + +# Estandarizar los datos +scaler = StandardScaler() +X_train = scaler.fit_transform(X_train) +X_test = scaler.transform(X_test) + +# Crear y entrenar el modelo +model = RandomForestClassifier(n_estimators=100, random_state=42) +model.fit(X_train, y_train) + +# Realizar predicciones +y_pred = model.predict(X_test) + +# Evaluar el modelo +print(confusion_matrix(y_test, y_pred)) +print(classification_report(y_test, y_pred)) + +# Guardar el modelo entrenado +import joblib +joblib.dump(model, 'fraud_detector_model.pkl') diff --git a/PROGRAMAS DE PYTHON/arbol.py b/PROGRAMAS DE PYTHON/arbol.py new file mode 100644 index 0000000..24bdedc --- /dev/null +++ b/PROGRAMAS DE PYTHON/arbol.py @@ -0,0 +1,33 @@ +from sklearn.tree import DecisionTreeClassifier +from sklearn.model_selection import train_test_split +from sklearn import metrics + +# Datos de ejemplo +# X representará las características (condiciones climáticas) y y será la etiqueta (deberías llevar un paraguas o no) +X = [[0, 1], [1, 0], [1, 1], [0, 0], [2, 2], [2, 0], [2, 1]] +y = [1, 1, 1, 0, 1, 0, 1] # 1: llevar paraguas, 0: no llevar paraguas + +# Dividir los datos en conjunto de entrenamiento y conjunto de prueba +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) + +# Crear el clasificador de árbol de decisión +clf = DecisionTreeClassifier() + +# Entrenar el modelo +clf.fit(X_train, y_train) + +# Hacer predicciones en el conjunto de prueba +y_pred = clf.predict(X_test) + +# Evaluar la precisión del modelo +accuracy = metrics.accuracy_score(y_test, y_pred) +print(f"Precisión del modelo: {accuracy * 100:.2f}%") + +# Ahora puedes utilizar el modelo para predecir si debes llevar un paraguas para nuevas condiciones climáticas +new_conditions = [[0, 1]] # Ejemplo: no está lloviendo, pero hay viento +prediction = clf.predict(new_conditions) + +if prediction[0] == 1: + print("Deberías llevar un paraguas.") +else: + print("No necesitas llevar un paraguas.") diff --git a/PROGRAMAS DE PYTHON/asistencia.txt b/PROGRAMAS DE PYTHON/asistencia.txt new file mode 100644 index 0000000..320a18e --- /dev/null +++ b/PROGRAMAS DE PYTHON/asistencia.txt @@ -0,0 +1,21 @@ +Gustavo +Paco +Clodomiro +x +x +x +x +xa +a +aq +w +s +ss +s +w +w + + +ss +s +sq diff --git a/PROGRAMAS DE PYTHON/audios.py b/PROGRAMAS DE PYTHON/audios.py new file mode 100644 index 0000000..ce6e1ae --- /dev/null +++ b/PROGRAMAS DE PYTHON/audios.py @@ -0,0 +1,22 @@ +import speech_recognition as sr + +def reconocer_voz(): + # Crear un objeto de reconocimiento de voz + r = sr.Recognizer() + + # Escuchar el audio del micrófono + with sr.Microphone() as source: + print("Di algo...") + audio = r.listen(source) + + # Intentar reconocer el texto + try: + texto = r.recognize_google(audio, language="es") + print("Has dicho: " + texto) + except sr.UnknownValueError: + print("No se pudo reconocer el audio") + except sr.RequestError as e: + print("Error al realizar la solicitud: {0}".format(e)) + +# Llamar a la función para iniciar el reconocimiento de voz +reconocer_voz() diff --git a/PROGRAMAS DE PYTHON/bosquealeatorio.py b/PROGRAMAS DE PYTHON/bosquealeatorio.py new file mode 100644 index 0000000..391b2b3 --- /dev/null +++ b/PROGRAMAS DE PYTHON/bosquealeatorio.py @@ -0,0 +1,22 @@ +from cryptography.hazmat.primitives.asymmetric import rsa +from cryptography.hazmat.primitives import serialization + +# Generar una nueva clave RSA de 2048 bits +private_key = rsa.generate_private_key( + public_exponent=65537, + key_size=2048, +) + +# Serializar la clave en formato PEM +pem = private_key.private_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PrivateFormat.PKCS8, + encryption_algorithm=serialization.NoEncryption(), +) + +# Cargar la clave serializada +loaded_private_key = serialization.load_pem_private_key(pem, password=None) + +# Imprimir la clave cargada +print(loaded_private_key) + diff --git a/PROGRAMAS DE PYTHON/bottwit.py b/PROGRAMAS DE PYTHON/bottwit.py new file mode 100644 index 0000000..7f03773 --- /dev/null +++ b/PROGRAMAS DE PYTHON/bottwit.py @@ -0,0 +1,59 @@ +import tweepy +import requests +from bs4 import BeautifulSoup +import time + +# Credenciales de API de Twitter +API_KEY = 'tu_api_key' +API_SECRET_KEY = 'tu_api_secret_key' +ACCESS_TOKEN = 'tu_access_token' +ACCESS_TOKEN_SECRET = 'tu_access_token_secret' + +# Autenticación en Twitter +auth = tweepy.OAuthHandler(API_KEY, API_SECRET_KEY) +auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET) +api = tweepy.API(auth) + +# URLs de RT Noticias y Sputnik +rt_url = 'https://www.rt.com/news/ukraine/' +sputnik_url = 'https://sputniknews.com/europe/' + +# Función para obtener noticias +def get_news(url): + response = requests.get(url) + soup = BeautifulSoup(response.content, 'html.parser') + headlines = soup.find_all('h2') + return [headline.get_text() for headline in headlines] + +# Función para hacer tweets sarcásticos +def post_sarcastic_tweet(): + sarcastic_tweets = [ + "Just when you thought things couldn't get more complicated in Ukraine...", + "Another day, another news from Ukraine. What's next?", + "Ukraine update: Because clearly, we needed more drama in the world.", + "Breaking news from Ukraine! Because regular news just isn't dramatic enough." + ] + tweet = random.choice(sarcastic_tweets) + api.update_status(tweet) + +# Función principal +def main(): + while True: + # Obtener y publicar noticias de RT + rt_news = get_news(rt_url) + for news in rt_news[:3]: # Limitar a 3 noticias para no exceder el límite de Twitter + api.update_status(f"RT Noticias: {news} #Ukraine") + + # Obtener y publicar noticias de Sputnik + sputnik_news = get_news(sputnik_url) + for news in sputnik_news[:3]: + api.update_status(f"Sputnik: {news} #Ukraine") + + # Publicar un tweet sarcástico + post_sarcastic_tweet() + + # Esperar 10 minutos + time.sleep(600) + +if __name__ == "__main__": + main() diff --git a/PROGRAMAS DE PYTHON/correctordepalabras.py b/PROGRAMAS DE PYTHON/correctordepalabras.py new file mode 100644 index 0000000..08595b1 --- /dev/null +++ b/PROGRAMAS DE PYTHON/correctordepalabras.py @@ -0,0 +1,39 @@ +import enchant + +def corregir_ortografia(archivo): + # Crear un diccionario de verificación ortográfica en inglés + d = enchant.Dict("en_US") + + # Leer el contenido del archivo + with open(archivo, 'r', encoding='utf-8') as f: + contenido = f.read() + + # Dividir el contenido en palabras + palabras = contenido.split() + + # Lista para almacenar las correcciones realizadas + correcciones = [] + + # Verificar ortografía y corregir palabras incorrectas + for palabra in palabras: + if not d.check(palabra): # Si la palabra no está en el diccionario + sugerencias = d.suggest(palabra) # Obtener sugerencias de corrección + if sugerencias: + correccion = sugerencias[0] # Tomar la primera sugerencia como corrección + correcciones.append((palabra, correccion)) # Guardar la palabra original y la corrección + contenido = contenido.replace(palabra, correccion) # Reemplazar en el contenido + + # Mostrar el contenido corregido por consola + print("Texto corregido:") + print(contenido) + + # Mostrar las correcciones realizadas + print("\nCorrecciones realizadas:") + for original, corregida in correcciones: + print(f"{original} -> {corregida}") + +# Solicitar al usuario el archivo que desea revisar +archivo = input("Ingrese el nombre del archivo que desea revisar (incluyendo la ruta si no está en el mismo directorio): ") + +# Llamar a la función para corregir ortografía y mostrar correcciones +corregir_ortografia(archivo) diff --git a/PROGRAMAS DE PYTHON/datos_transacciones.csv b/PROGRAMAS DE PYTHON/datos_transacciones.csv new file mode 100644 index 0000000..9ab6000 --- /dev/null +++ b/PROGRAMAS DE PYTHON/datos_transacciones.csv @@ -0,0 +1,4 @@ +monto,hora,ubicacion,tipo_tarjeta,fraude +100,13,EEUU,debito,0 +200,15,Canadá,credito,0 +500,10,México,debito,1 \ No newline at end of file diff --git a/PROGRAMAS DE PYTHON/defenderarchivo.py b/PROGRAMAS DE PYTHON/defenderarchivo.py new file mode 100644 index 0000000..af18307 --- /dev/null +++ b/PROGRAMAS DE PYTHON/defenderarchivo.py @@ -0,0 +1,48 @@ +import os +import time +import shutil +from watchdog.observers import Observer +from watchdog.events import FileSystemEventHandler + +# Carpeta a monitorear +folder_to_watch = "C:/Users/Username/Desktop/FirewallFolder" + +# Función para verificar si un archivo es sospechoso +def is_suspicious(file_path): + # Implementación básica de detección: solo verifica la extensión + suspicious_extensions = ['.exe', '.bat', '.vbs', '.js'] # Ejemplo de extensiones sospechosas + + _, file_extension = os.path.splitext(file_path) + if file_extension.lower() in suspicious_extensions: + return True + return False + +# Manejador de eventos para el monitor de la carpeta +class FolderMonitor(FileSystemEventHandler): + def on_created(self, event): + if not event.is_directory: + file_path = event.src_path + if is_suspicious(file_path): + print(f"Archivo sospechoso detectado: {file_path}") + # Aquí podrías implementar acciones como mover el archivo a cuarentena + # shutil.move(file_path, "ruta a carpeta de cuarentena") + else: + print(f"Archivo seguro detectado: {file_path}") + +# Función principal para iniciar el monitoreo +def start_firewall(): + event_handler = FolderMonitor() + observer = Observer() + observer.schedule(event_handler, folder_to_watch, recursive=True) + observer.start() + print(f"Monitoreando la carpeta: {folder_to_watch}") + + try: + while True: + time.sleep(1) + except KeyboardInterrupt: + observer.stop() + observer.join() + +if __name__ == "__main__": + start_firewall() diff --git a/PROGRAMAS DE PYTHON/faltasdeorografia.txt b/PROGRAMAS DE PYTHON/faltasdeorografia.txt new file mode 100644 index 0000000..c2a6fd0 --- /dev/null +++ b/PROGRAMAS DE PYTHON/faltasdeorografia.txt @@ -0,0 +1 @@ +This text contains some spelling mistakes. For example, "teh", "problam", "occured", "writting", "abowt", "defenetly", "apologise", "seperate", "dissapointed", "begining", "beleive", "neccesary", "expeirence", "succesful", "sugestion", "ocassionally", "happened", "occured", "wether", "truely", "immediatly", "embarassing", "ocassion", "completly". diff --git a/PROGRAMAS DE PYTHON/juegoderol.py b/PROGRAMAS DE PYTHON/juegoderol.py new file mode 100644 index 0000000..d53e95e --- /dev/null +++ b/PROGRAMAS DE PYTHON/juegoderol.py @@ -0,0 +1,131 @@ +def print_welcome_message(): + print(""" + ==================================== + Bienvenido al Juego de Aventura Textual + ==================================== + """) + print(""" + _.--. + _.-'_:-'|| + _.-'_.-::::'|| + _.-:'_.-::::::' || +.'`-.-:::::::' || +/.'`;|:::::::' ||_ +|| ||::::::' _.;._'-._ +|| ||:::::' _.-!oo @.!-._'-. +\\'. ||:::::.-!()oo @!()@.-'_.| +'.'-;|:.-'.&$@.& ()$%-'o.'\\U|| + `>'-.!@%()@'@_%-'_.-o _.|'|| + ||-._'-.@.-'_.-' _.-o |'|| + ||=[ '-._.-\\U/.-' o |'|| + || '-.]=|| |'| o |'|| + || || |'| _| '; + || || |'| _.-'_.-' + |'-._ || |'|_.-'_.-' + '-._'-.|| |' `_.-' + '-.||_/.-' + """) + +def make_choice(prompt, options): + choice = None + while choice not in options: + print(prompt) + for key, value in options.items(): + print(f"{key}: {value}") + choice = input("Elige una opción: ").strip().lower() + return choice + +def cave_adventure(): + print("Te despiertas en una cueva oscura. Hay dos túneles frente a ti.") + choice = make_choice("¿Cuál túnel tomas?", {'a': 'Túnel izquierdo', 'b': 'Túnel derecho'}) + + if choice == 'a': + print("Caminas por el túnel izquierdo y encuentras un cofre.") + choice = make_choice("¿Abres el cofre?", {'a': 'Sí', 'b': 'No'}) + + if choice == 'a': + print("¡Encuentras un tesoro! Sigues adelante y ves una luz al final del túnel.") + forest_adventure() + else: + print("Decides no abrir el cofre y continúas caminando.") + print("Te pierdes en la oscuridad y encuentras una bifurcación.") + choice = make_choice("¿Qué dirección tomas?", {'a': 'Izquierda', 'b': 'Derecha'}) + + if choice == 'a': + print("Encuentras una salida de la cueva, pero estás en un bosque oscuro.") + forest_adventure() + else: + print("Te encuentras con un dragón. Has perdido el juego.") + else: + print("Caminas por el túnel derecho y te encuentras con un dragón.") + choice = make_choice("¿Luchas contra el dragón?", {'a': 'Sí', 'b': 'No'}) + + if choice == 'a': + print("Luchas valientemente, pero el dragón es demasiado fuerte. Has perdido el juego.") + else: + print("Huyes rápidamente y encuentras una salida de la cueva. Has sobrevivido.") + forest_adventure() + +def forest_adventure(): + print("Te encuentras en un bosque denso. Hay un sendero que se divide en dos.") + choice = make_choice("¿Qué camino tomas?", {'a': 'Sendero izquierdo', 'b': 'Sendero derecho'}) + + if choice == 'a': + print("Sigues el sendero izquierdo y encuentras una cabaña.") + choice = make_choice("¿Entras a la cabaña?", {'a': 'Sí', 'b': 'No'}) + + if choice == 'a': + print("Entras a la cabaña y encuentras provisiones. Recuperas fuerzas y decides explorar más.") + mountain_adventure() + else: + print("Decides no entrar a la cabaña y sigues caminando.") + print("Te pierdes en el bosque y nunca encuentras la salida. Has perdido el juego.") + else: + print("Sigues el sendero derecho y encuentras un río.") + river_adventure() + +def river_adventure(): + print("Te encuentras en un río caudaloso. Hay un puente y un bote.") + choice = make_choice("¿Qué decides hacer?", {'a': 'Cruzar el puente', 'b': 'Usar el bote'}) + + if choice == 'a': + print("Cruzas el puente y llegas a una aldea. Los aldeanos te ayudan y finalmente encuentras el camino a casa. ¡Has ganado el juego!") + else: + print("Usas el bote, pero la corriente es muy fuerte y el bote se vuelca. Has perdido el juego.") + +def mountain_adventure(): + print("Te encuentras al pie de una montaña. Hay un sendero empinado y una cueva.") + choice = make_choice("¿Qué decides hacer?", {'a': 'Subir la montaña', 'b': 'Entrar en la cueva'}) + + if choice == 'a': + print("Subes la montaña y encuentras un monasterio. Los monjes te ofrecen refugio y sabiduría.") + choice = make_choice("¿Aceptas quedarte con los monjes?", {'a': 'Sí', 'b': 'No'}) + + if choice == 'a': + print("Aprendes mucho de los monjes y encuentras paz interior. Has encontrado un nuevo hogar. ¡Has ganado el juego!") + else: + print("Decides seguir tu camino y desciendes por el otro lado de la montaña, encontrando una nueva aventura.") + print("Encuentras un valle lleno de vida y decides establecerte allí. ¡Has ganado el juego!") + else: + print("Entras en la cueva y encuentras un lago subterráneo.") + choice = make_choice("¿Nadas a través del lago?", {'a': 'Sí', 'b': 'No'}) + + if choice == 'a': + print("Nadas a través del lago y encuentras una salida secreta. Te lleva a un hermoso jardín.") + choice = make_choice("¿Exploras el jardín?", {'a': 'Sí', 'b': 'No'}) + + if choice == 'a': + print("Exploras el jardín y encuentras una comunidad secreta de sabios. Aprendes de ellos y vives en armonía. ¡Has ganado el juego!") + else: + print("Decides no explorar el jardín y sigues adelante.") + print("Encuentras un desierto y te pierdes en la arena. Has perdido el juego.") + else: + print("Decides no nadar y vuelves al pie de la montaña.") + mountain_adventure() + +def start_adventure(): + print_welcome_message() + cave_adventure() + +if __name__ == "__main__": + start_adventure() diff --git a/PROGRAMAS DE PYTHON/ordenadordearchivos.py b/PROGRAMAS DE PYTHON/ordenadordearchivos.py new file mode 100644 index 0000000..93f41aa --- /dev/null +++ b/PROGRAMAS DE PYTHON/ordenadordearchivos.py @@ -0,0 +1,24 @@ +import os + +def ordenar_archivos_por_nombre(ruta_carpeta): + # Verificar si la ruta es válida y es un directorio + if not os.path.isdir(ruta_carpeta): + print(f"La ruta especificada '{ruta_carpeta}' no es un directorio válido.") + return + + # Obtener la lista de archivos en la carpeta + archivos = os.listdir(ruta_carpeta) + + # Ordenar los archivos por nombre (orden alfabético) + archivos.sort() + + # Mostrar los archivos ordenados + print(f"Archivos en '{ruta_carpeta}', ordenados alfabéticamente:") + for archivo in archivos: + print(archivo) + +# Solicitar la ruta de la carpeta al usuario +ruta = input("Ingrese la ruta de la carpeta que desea ordenar: ") + +# Llamar a la función para ordenar y mostrar los archivos +ordenar_archivos_por_nombre(ruta) diff --git a/PROGRAMAS DE PYTHON/prediccion.py b/PROGRAMAS DE PYTHON/prediccion.py new file mode 100644 index 0000000..1e29566 --- /dev/null +++ b/PROGRAMAS DE PYTHON/prediccion.py @@ -0,0 +1,28 @@ +from sklearn.datasets import load_iris +from sklearn.model_selection import train_test_split +from sklearn.neighbors import KNeighborsClassifier +from sklearn.metrics import accuracy_score + +# Paso 1: Cargar el conjunto de datos +iris = load_iris() +X = iris.data +y = iris.target + +# Paso 2: Dividir el conjunto de datos en conjuntos de entrenamiento y prueba +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) + +# Paso 3: Crear y entrenar el modelo +clf = KNeighborsClassifier(n_neighbors=3) +clf.fit(X_train, y_train) + +# Paso 4: Realizar predicciones +y_pred = clf.predict(X_test) + +# Paso 5: Evaluar el rendimiento del modelo +precision = accuracy_score(y_test, y_pred) +print("Precisión del modelo:", precision) + +# Paso 6: Utilizar el modelo para hacer predicciones nuevas +nuevas_caracteristicas = [[5.1, 3.5, 1.4, 0.2]] # Nuevas características de una flor +prediccion = clf.predict(nuevas_caracteristicas) +print("Predicción:", iris.target_names[prediccion]) diff --git a/PROGRAMAS DE PYTHON/recordardora.py b/PROGRAMAS DE PYTHON/recordardora.py new file mode 100644 index 0000000..91f86da --- /dev/null +++ b/PROGRAMAS DE PYTHON/recordardora.py @@ -0,0 +1,44 @@ +import schedule +import time +import smtplib +from email.mime.multipart import MIMEMultipart +from email.mime.text import MIMEText + +# Configuración del correo electrónico +def send_email(subject, body): + # Configura los detalles de tu servidor de correo electrónico + from_email = 'tu_correo@gmail.com' + from_password = 'tu_contraseña' + to_email = 'destinatario@gmail.com' + + msg = MIMEMultipart() + msg['From'] = from_email + msg['To'] = to_email + msg['Subject'] = subject + + msg.attach(MIMEText(body, 'plain')) + + try: + server = smtplib.SMTP('smtp.gmail.com', 587) + server.starttls() + server.login(from_email, from_password) + text = msg.as_string() + server.sendmail(from_email, to_email, text) + server.quit() + print("Email sent successfully") + except Exception as e: + print(f"Failed to send email: {str(e)}") + +# Función para enviar recordatorio +def send_task_reminder(): + subject = "Recordatorio de Tarea" + body = "Recuerda completar tus tareas!" + send_email(subject, body) + +# Programar el recordatorio para cada hora +schedule.every().hour.do(send_task_reminder) + +# Bucle principal para ejecutar las tareas programadas +while True: + schedule.run_pending() + time.sleep(1) diff --git a/PROGRAMAS DE PYTHON/vulnerabilidad.py b/PROGRAMAS DE PYTHON/vulnerabilidad.py new file mode 100644 index 0000000..37519ad --- /dev/null +++ b/PROGRAMAS DE PYTHON/vulnerabilidad.py @@ -0,0 +1,22 @@ +import pandas as pd +from sklearn.model_selection import train_test_split +from sklearn.ensemble import RandomForestClassifier +from sklearn.metrics import classification_report + +# Cargar los datos de vulnerabilidades en el sistema de seguridad +data = pd.read_csv("datos_vulnerabilidades.csv") + +# Preprocesamiento de datos (eliminación de valores nulos, codificación de variables categóricas, etc.) + +# Dividir los datos en conjuntos de entrenamiento y prueba +X = data.drop("vulnerable", axis=1) +y = data["vulnerable"] +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) + +# Entrenar un clasificador de bosque aleatorio +clf = RandomForestClassifier() +clf.fit(X_train, y_train) + +# Evaluar el modelo +y_pred = clf.predict(X_test) +print(classification_report(y_test, y_pred)) diff --git a/PROGRAMAS DE PYTHON/vulnerabilidad2.py b/PROGRAMAS DE PYTHON/vulnerabilidad2.py new file mode 100644 index 0000000..f9883aa --- /dev/null +++ b/PROGRAMAS DE PYTHON/vulnerabilidad2.py @@ -0,0 +1,31 @@ +import pandas as pd +import numpy as np +from sklearn.ensemble import IsolationForest +from sklearn.preprocessing import StandardScaler +from sklearn.model_selection import train_test_split +from sklearn.metrics import classification_report + +# Cargar los datos de los registros de eventos de seguridad +data = pd.read_csv("datos_registros_eventos.csv") + +# Seleccionar las características relevantes y normalizar los datos +X = data[['feature1', 'feature2', 'feature3']] +scaler = StandardScaler() +X_scaled = scaler.fit_transform(X) + +# Dividir los datos en conjuntos de entrenamiento y prueba +X_train, X_test = train_test_split(X_scaled, test_size=0.2, random_state=42) + +# Entrenar un modelo de detección de anomalías con Isolation Forest +clf = IsolationForest(contamination=0.05) +clf.fit(X_train) + +# Predecir las anomalías en los datos de prueba +y_pred = clf.predict(X_test) + +# Evaluar las predicciones +y_pred[y_pred == 1] = 0 # Anomalía si el valor es 1 +y_pred[y_pred == -1] = 1 # No anomalía si el valor es -1 + +# Imprimir métricas de evaluación del modelo +print(classification_report(y_test, y_pred)) diff --git a/PROGRAMAS DE PYTHON/vulnerabilidad3.py b/PROGRAMAS DE PYTHON/vulnerabilidad3.py new file mode 100644 index 0000000..9f4c6d5 --- /dev/null +++ b/PROGRAMAS DE PYTHON/vulnerabilidad3.py @@ -0,0 +1,33 @@ +import pandas as pd +from sklearn.preprocessing import StandardScaler +from sklearn.model_selection import train_test_split +from sklearn.neural_network import MLPClassifier +from sklearn.metrics import classification_report + +# Cargar los datos del conjunto de datos NSL-KDD +data = pd.read_csv("nsl-kdd.csv") + +# Preprocesamiento de datos +# Eliminar columnas no relevantes y codificar variables categóricas + +# Separar características y etiquetas +X = data.drop("label", axis=1) +y = data["label"] + +# Dividir los datos en conjuntos de entrenamiento y prueba +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) + +# Normalizar los datos +scaler = StandardScaler() +X_train = scaler.fit_transform(X_train) +X_test = scaler.transform(X_test) + +# Entrenar un clasificador de redes neuronales +clf = MLPClassifier(hidden_layer_sizes=(100, 50), max_iter=1000, random_state=42) +clf.fit(X_train, y_train) + +# Realizar predicciones en el conjunto de prueba +y_pred = clf.predict(X_test) + +# Imprimir métricas de evaluación del modelo +print(classification_report(y_test, y_pred)) diff --git a/PROGRAMAS DE PYTHON/vulnerabilidad4.py b/PROGRAMAS DE PYTHON/vulnerabilidad4.py new file mode 100644 index 0000000..487fcba --- /dev/null +++ b/PROGRAMAS DE PYTHON/vulnerabilidad4.py @@ -0,0 +1,30 @@ +import pandas as pd +from sklearn.preprocessing import StandardScaler +from sklearn.cluster import DBSCAN +from sklearn.metrics import classification_report + +# Cargar los datos del conjunto de datos CICIDS 2017 +data = pd.read_csv("cicids_2017.csv") + +# Preprocesamiento de datos +# Eliminar columnas no relevantes y codificar variables categóricas + +# Separar características y etiquetas +X = data.drop("label", axis=1) +y = data["label"] + +# Normalizar los datos +scaler = StandardScaler() +X_scaled = scaler.fit_transform(X) + +# Entrenar un modelo de detección de anomalías con DBSCAN +clf = DBSCAN(eps=0.5, min_samples=10) +clf.fit(X_scaled) + +# Asignar etiquetas de anomalía (-1) y no anomalía (1) a los datos +y_pred = clf.labels_ +y_pred[y_pred == 0] = 1 # Clases identificadas como normales +y_pred[y_pred == -1] = 0 # Clases identificadas como anormales + +# Imprimir métricas de evaluación del modelo +print(classification_report(y, y_pred)) diff --git a/PROGRAMAS DE PYTHON/vulnerabilidad6.py b/PROGRAMAS DE PYTHON/vulnerabilidad6.py new file mode 100644 index 0000000..780b29d --- /dev/null +++ b/PROGRAMAS DE PYTHON/vulnerabilidad6.py @@ -0,0 +1,55 @@ +import pandas as pd +from sklearn.model_selection import train_test_split +from sklearn.preprocessing import LabelEncoder +from tensorflow.keras.preprocessing.text import Tokenizer +from tensorflow.keras.preprocessing.sequence import pad_sequences +from tensorflow.keras.models import Sequential +from tensorflow.keras.layers import Embedding, Conv1D, MaxPooling1D, Flatten, Dense + +# Cargar los datos del conjunto de datos de correos electrónicos +data = pd.read_csv("phishing_emails.csv") + +# Preprocesamiento de datos +X = data['email_text'] +y = data['label'] + +# Codificar las etiquetas de clase +label_encoder = LabelEncoder() +y = label_encoder.fit_transform(y) + +# Tokenizar el texto de los correos electrónicos y convertirlos en secuencias numéricas +tokenizer = Tokenizer() +tokenizer.fit_on_texts(X) +X_sequences = tokenizer.texts_to_sequences(X) + +# Ajustar las secuencias a una longitud fija y crear un arreglo numpy +max_sequence_length = 1000 # longitud máxima de la secuencia +X_pad = pad_sequences(X_sequences, maxlen=max_sequence_length) + +# Dividir los datos en conjuntos de entrenamiento y prueba +X_train, X_test, y_train, y_test = train_test_split(X_pad, y, test_size=0.2, random_state=42) + +# Construir el modelo de CNN +embedding_dim = 50 # dimensión del embedding +vocab_size = len(tokenizer.word_index) + 1 # tamaño del vocabulario + +model = Sequential([ + Embedding(vocab_size, embedding_dim, input_length=max_sequence_length), + Conv1D(128, 5, activation='relu'), + MaxPooling1D(5), + Conv1D(128, 5, activation='relu'), + MaxPooling1D(5), + Flatten(), + Dense(128, activation='relu'), + Dense(1, activation='sigmoid') +]) + +model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) + +# Entrenar el modelo +model.fit(X_train, y_train, epochs=5, batch_size=32, validation_data=(X_test, y_test)) + +# Evaluar el modelo en el conjunto de prueba +loss, accuracy = model.evaluate(X_test, y_test) +print(f"Pérdida en el conjunto de prueba: {loss}") +print(f"Precisión en el conjunto de prueba: {accuracy}") diff --git a/README.md b/README.md index 4d2a3da..ae392ff 100644 --- a/README.md +++ b/README.md @@ -1 +1,3 @@ -# Python_programs \ No newline at end of file +# Python_programs + +"I have uploaded a file with several Python codes that I believe will be of great help and contribution to the Python community. These codes address different topics and common problems in developing with Python, such as classification algorithms, data manipulation, visualization of graphics and much more. I hope this collection of code is useful to other Python developers and can foster knowledge sharing and community growth. I'm excited to share my work and contribute in this way!"