├── .vscode └── settings.json ├── EjemplosPracticos ├── EJ01-DeteccionCoches │ ├── EjemploCoches.py │ ├── alumnos.jpg │ └── cars_4.jpg ├── EJ02-ReconocimientoVideoCara │ └── EjemploReconocimientoVideoCara.py ├── EJ03-ReconocimientoVideoObjetos │ └── EjemploReconocimientoVideoObjetos.py ├── EJ04-ReconocimientoVozBusqueda │ └── reconocer.py └── EJ05-TextoAVoz │ └── textoAVoz.py ├── NoSupervisado ├── InterpretarResultados.py ├── NoSupervisadoKMeans.py └── dataPrediccion.json ├── Presentaciones auxiliares ├── 0- Introduccion - Introduccion al aprendizaje automatico.odp ├── 0- Introduccion - Introduccion al aprendizaje automatico.pdf ├── 1- Conceptos previos - Introduccion al aprendizaje automatico.odp ├── 1- Conceptos previos - Introduccion al aprendizaje automatico.pdf ├── 2- Aprendizaje Supervisado - Introduccion al aprendizaje automatico.odp ├── 2- Aprendizaje Supervisado - Introduccion al aprendizaje automatico.pdf ├── 3- Aprendizaje Supervisado CASO ESTUDIO - Introduccion al aprendizaje automatico.odp ├── 3- Aprendizaje Supervisado CASO ESTUDIO - Introduccion al aprendizaje automatico.pdf ├── 4- Aprendizaje No supervisado - Introduccion al aprendizaje automatico.odp ├── 4- Aprendizaje No supervisado - Introduccion al aprendizaje automatico.pdf ├── 5- Aprendizaje No supervisado CASO ESTUDIO- Introduccion al aprendizaje automatico.odp └── 5- Aprendizaje No supervisado CASO ESTUDIO- Introduccion al aprendizaje automatico.pdf ├── README.md ├── Supervisado ├── Clasificacion │ ├── 3EnRayaConScore │ │ ├── 3EnRayaJuego.py │ │ ├── EntrenarModeloTree.py │ │ ├── modelTree3EnRaya.pkl │ │ ├── modelTree3EnRaya1000.pkl │ │ ├── modelTree3EnRaya2.pkl │ │ ├── modelTree3EnRaya20000.pkl │ │ └── modelTree3EnRaya50000.pkl │ ├── 3EnRayaSinScore │ │ ├── 3EnRayaJuegoSinScore.py │ │ ├── EntrenarModeloSVM.py │ │ ├── modelTree3EnRaya1000.pkl │ │ └── modelTree3EnRaya2.pkl │ ├── GenerarPartidas3EnRaya.py │ ├── data1.json │ ├── data1000.json │ ├── data2.json │ ├── data20000.json │ └── data50000.json └── Regresion │ ├── ConsultarPrecioPiso.py │ ├── RegresionPisos.py │ └── modeloRegresion.pkl ├── Taller - Introduccion al aprendizaje automatico (Supervisado y no supervisado).odp └── Taller - Introduccion al aprendizaje automatico (Supervisado y no supervisado).pdf /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.pythonPath": "C:\\Program Files (x86)\\Python38-32\\python.exe" 3 | } -------------------------------------------------------------------------------- /EjemplosPracticos/EJ01-DeteccionCoches/EjemploCoches.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | 4 | #pip3 install --upgrade opencv-python pillow tensorflow cvlib numpy 5 | #OJO Error con version moderna de opencv-python https://stackoverflow.com/questions/69719025/cvlib-causing-indexerror-invalid-index-to-scalar-variable 6 | #Se arregla con pip3 install opencv-python==4.5.3.56) 7 | 8 | import cv2 9 | import matplotlib.pyplot as plt 10 | import cvlib as cv 11 | from cvlib.object_detection import draw_bbox 12 | 13 | 14 | im = cv2.imread('cars_4.jpg') 15 | 16 | bbox, label, conf = cv.detect_common_objects(im) 17 | output_image = draw_bbox(im, bbox, label, conf) 18 | plt.imshow(output_image) 19 | plt.show() 20 | print('Number of cars in the image is '+ str(label.count('car'))) 21 | -------------------------------------------------------------------------------- /EjemplosPracticos/EJ01-DeteccionCoches/alumnos.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sergarb1/TallerAprendizajeAutomaticoPython/834c2e8b3e1b9cf26d72fe552232e016dd842902/EjemplosPracticos/EJ01-DeteccionCoches/alumnos.jpg -------------------------------------------------------------------------------- /EjemplosPracticos/EJ01-DeteccionCoches/cars_4.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sergarb1/TallerAprendizajeAutomaticoPython/834c2e8b3e1b9cf26d72fe552232e016dd842902/EjemplosPracticos/EJ01-DeteccionCoches/cars_4.jpg -------------------------------------------------------------------------------- /EjemplosPracticos/EJ02-ReconocimientoVideoCara/EjemploReconocimientoVideoCara.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | 4 | #pip3 install --upgrade opencv-python pillow tensorflow cvlib numpy 5 | #OJO Error con version moderna de opencv-python https://stackoverflow.com/questions/69719025/cvlib-causing-indexerror-invalid-index-to-scalar-variable 6 | #Se arregla con pip3 install opencv-python==4.5.3.56) 7 | 8 | import cv2 9 | 10 | # Enable camera 11 | cap = cv2.VideoCapture(0) 12 | cap.set(3, 640) 13 | cap.set(4, 420) 14 | 15 | # import cascade file for facial recognition 16 | faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml") 17 | 18 | 19 | # if you want to detect any object for example eyes, use one more layer of classifier as below: 20 | eyeCascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_eye_tree_eyeglasses.xml") 21 | 22 | while True: 23 | success, img = cap.read() 24 | imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 25 | 26 | # Getting corners around the face 27 | faces = faceCascade.detectMultiScale(imgGray, 1.3, 5) # 1.3 = scale factor, 5 = minimum neighbor 28 | # drawing bounding box around face 29 | for (x, y, w, h) in faces: 30 | img = cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 3) 31 | 32 | 33 | # detecting eyes 34 | eyes = eyeCascade.detectMultiScale(imgGray) 35 | # drawing bounding box for eyes 36 | for (ex, ey, ew, eh) in eyes: 37 | img = cv2.rectangle(img, (ex, ey), (ex+ew, ey+eh), (255, 0, 0), 3) 38 | 39 | cv2.imshow('face_detect', img) 40 | if cv2.waitKey(10) & 0xFF == ord('q'): 41 | break 42 | cap.release() 43 | cv2.destroyWindow('face_detect') 44 | 45 | -------------------------------------------------------------------------------- /EjemplosPracticos/EJ03-ReconocimientoVideoObjetos/EjemploReconocimientoVideoObjetos.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | 4 | #pip3 install --upgrade opencv-python pillow tensorflow cvlib numpy 5 | #OJO Error con version moderna de opencv-python https://stackoverflow.com/questions/69719025/cvlib-causing-indexerror-invalid-index-to-scalar-variable 6 | #Se arregla con pip3 install opencv-python==4.5.3.56) 7 | 8 | 9 | import cv2 10 | import cvlib as cv 11 | from cvlib.object_detection import draw_bbox 12 | 13 | # Enable camera 14 | cap = cv2.VideoCapture(0) 15 | cap.set(3, 640) 16 | cap.set(4, 420) 17 | 18 | while True: 19 | success, img = cap.read() 20 | 21 | bbox, label, conf = cv.detect_common_objects(img) 22 | print('Number of keyboards in the image is '+ str(label.count('keyboard'))) 23 | 24 | output_image = draw_bbox(img, bbox, label, conf) 25 | 26 | cv2.imshow('cars_detect', output_image) 27 | if cv2.waitKey(10) & 0xFF == ord('q'): 28 | break 29 | cap.release() 30 | cv2.destroyWindow('cars_detect') 31 | 32 | -------------------------------------------------------------------------------- /EjemplosPracticos/EJ04-ReconocimientoVozBusqueda/reconocer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | 4 | 5 | #sudo apt-get install python3-pyaudio pavucontrol 6 | #pip3 install SpeechRecognition pyaudio 7 | import speech_recognition as sr 8 | import webbrowser 9 | 10 | 11 | reconocedor = sr.Recognizer() 12 | #print(sr.Microphone.list_microphone_names()) 13 | with sr.Microphone() as entradasVoz: 14 | print("Por favor, hable ahora y diga que quiere buscar en Youtube") 15 | escuchando = reconocedor.listen(entradasVoz) 16 | print("Analizando...") 17 | try: 18 | fraseReconocida=reconocedor.recognize_google(escuchando,language = "es-ES") 19 | print("Dijiste: "+fraseReconocida) 20 | webbrowser.open('https://www.youtube.com/results?search_query='+fraseReconocida) 21 | 22 | 23 | except: 24 | print("Por favor, hable de nuevo") -------------------------------------------------------------------------------- /EjemplosPracticos/EJ05-TextoAVoz/textoAVoz.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | #pip3 install gtts 4 | #sudo apt install mpg321 5 | from gtts import gTTS 6 | import os 7 | tts = gTTS('Van dos tomates y uno dice ay va, que frio hace. Y el otro responde: ay va, un tomate que habla', lang='es-ES') 8 | 9 | with open("tmp.mp3", "wb") as archivo: 10 | tts.write_to_fp(archivo) 11 | os.system("mpg321 tmp.mp3") 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | ''' 31 | #pip3 install pyttsx3 32 | #sudo apt install espeak 33 | import pyttsx3 34 | engine = pyttsx3.init() 35 | engine.setProperty('rate', 120) 36 | engine.setProperty('voice', 'spanish') 37 | engine.setProperty('volume', 1) 38 | 39 | 40 | # It's just a text to speech function.. 41 | def saySomething(somethingToSay): 42 | engine.say(somethingToSay) 43 | engine.runAndWait() 44 | 45 | 46 | while True: 47 | something = input("Something to say? ") 48 | print("Saying something with speakers..") 49 | saySomething(something) 50 | 51 | ''' -------------------------------------------------------------------------------- /NoSupervisado/InterpretarResultados.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | #Incluimos biblioteca para trabaja con JSON 4 | import json 5 | 6 | #Cargamos el JSON de los datos de la prediccion 7 | with open('./dataPrediccion.json') as file: 8 | data = json.load(file) 9 | 10 | 11 | print("Resumen con interpretacion nuestra") 12 | #Tabla donde damos una etiqueta a cada prediccion 13 | #La primera etiqueta es para la prediccion 0, luego la 1, etc... 14 | TraduccionPosicion=["Asistente","Goleador","Goleador y asistente", "Nada"] 15 | 16 | for i in range(len(data)): 17 | cad="Goles "+str(data[i][0])+ " Asistencias "+str(data[i][1]) 18 | cad=cad+" =====> Prediccion:"+TraduccionPosicion[int(data[i][2])] 19 | print(cad) 20 | print("") -------------------------------------------------------------------------------- /NoSupervisado/NoSupervisadoKMeans.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #Bibliotecas importadas para usar 3 | from sklearn import cluster 4 | 5 | #Incluimos biblioteca para trabaja con JSON 6 | import json 7 | 8 | #Corpus a clasificar, de goles y asistencias de un jugado 9 | golesAsistencias=[[20,12],[30,16],[0,1],[1,0],[1,16],[2,16],[1,12],[2,14],[20,3],[18,1],[17,0],[20,3],[33,20]] 10 | 11 | #Usamos algoritmo KMeans de Clustering, suponiendo 4 clusteres 12 | # https://en.wikipedia.org/wiki/K-means_clustering 13 | k_means = cluster.KMeans(n_clusters=4) 14 | 15 | #Entrenamos el modelo 16 | k_means.fit(golesAsistencias) 17 | 18 | #obtemos en values "los centros" de cada grupo 19 | values = k_means.cluster_centers_.squeeze() 20 | print("Valores Centros") 21 | print(values) 22 | 23 | 24 | #Obtenemos las etiquetas de cada prediccion del entrenamiento 25 | labels = k_means.labels_ 26 | print("Etiquetas") 27 | print(labels) 28 | 29 | #Ejemplo de predecir un nuevo valor, a ver en que cluster iria 30 | res=k_means.predict([[34,1]]) 31 | print("Prediccion") 32 | print(res) 33 | 34 | #Guardamos los datos, con sus etiquetas generadas 35 | #En la variable data, almacenamos la combinacion de los ejemplos 36 | #anyandiendo al final su etiqueta 37 | data=[] 38 | for i in range(len(golesAsistencias)): 39 | data.append([golesAsistencias[i][0],golesAsistencias[i][1],str(labels[i])]) 40 | 41 | #Guardamos el contenido de data en un JSON 42 | with open('dataPrediccion.json', 'w') as outfile: 43 | json.dump(data, outfile) -------------------------------------------------------------------------------- /NoSupervisado/dataPrediccion.json: -------------------------------------------------------------------------------- 1 | [[20, 12, "1"], [30, 16, "2"], [0, 1, "3"], [1, 0, "3"], [1, 16, "0"], [2, 16, "0"], [1, 12, "0"], [2, 14, "0"], [20, 3, "1"], [18, 1, "1"], [17, 0, "1"], [20, 3, "1"], [33, 20, "2"]] -------------------------------------------------------------------------------- /Presentaciones auxiliares/0- Introduccion - Introduccion al aprendizaje automatico.odp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sergarb1/TallerAprendizajeAutomaticoPython/834c2e8b3e1b9cf26d72fe552232e016dd842902/Presentaciones auxiliares/0- Introduccion - Introduccion al aprendizaje automatico.odp -------------------------------------------------------------------------------- /Presentaciones auxiliares/0- Introduccion - Introduccion al aprendizaje automatico.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sergarb1/TallerAprendizajeAutomaticoPython/834c2e8b3e1b9cf26d72fe552232e016dd842902/Presentaciones auxiliares/0- Introduccion - Introduccion al aprendizaje automatico.pdf -------------------------------------------------------------------------------- /Presentaciones auxiliares/1- Conceptos previos - Introduccion al aprendizaje automatico.odp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sergarb1/TallerAprendizajeAutomaticoPython/834c2e8b3e1b9cf26d72fe552232e016dd842902/Presentaciones auxiliares/1- Conceptos previos - Introduccion al aprendizaje automatico.odp -------------------------------------------------------------------------------- /Presentaciones auxiliares/1- Conceptos previos - Introduccion al aprendizaje automatico.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sergarb1/TallerAprendizajeAutomaticoPython/834c2e8b3e1b9cf26d72fe552232e016dd842902/Presentaciones auxiliares/1- Conceptos previos - Introduccion al aprendizaje automatico.pdf -------------------------------------------------------------------------------- /Presentaciones auxiliares/2- Aprendizaje Supervisado - Introduccion al aprendizaje automatico.odp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sergarb1/TallerAprendizajeAutomaticoPython/834c2e8b3e1b9cf26d72fe552232e016dd842902/Presentaciones auxiliares/2- Aprendizaje Supervisado - Introduccion al aprendizaje automatico.odp -------------------------------------------------------------------------------- /Presentaciones auxiliares/2- Aprendizaje Supervisado - Introduccion al aprendizaje automatico.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sergarb1/TallerAprendizajeAutomaticoPython/834c2e8b3e1b9cf26d72fe552232e016dd842902/Presentaciones auxiliares/2- Aprendizaje Supervisado - Introduccion al aprendizaje automatico.pdf -------------------------------------------------------------------------------- /Presentaciones auxiliares/3- Aprendizaje Supervisado CASO ESTUDIO - Introduccion al aprendizaje automatico.odp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sergarb1/TallerAprendizajeAutomaticoPython/834c2e8b3e1b9cf26d72fe552232e016dd842902/Presentaciones auxiliares/3- Aprendizaje Supervisado CASO ESTUDIO - Introduccion al aprendizaje automatico.odp -------------------------------------------------------------------------------- /Presentaciones auxiliares/3- Aprendizaje Supervisado CASO ESTUDIO - Introduccion al aprendizaje automatico.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sergarb1/TallerAprendizajeAutomaticoPython/834c2e8b3e1b9cf26d72fe552232e016dd842902/Presentaciones auxiliares/3- Aprendizaje Supervisado CASO ESTUDIO - Introduccion al aprendizaje automatico.pdf -------------------------------------------------------------------------------- /Presentaciones auxiliares/4- Aprendizaje No supervisado - Introduccion al aprendizaje automatico.odp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sergarb1/TallerAprendizajeAutomaticoPython/834c2e8b3e1b9cf26d72fe552232e016dd842902/Presentaciones auxiliares/4- Aprendizaje No supervisado - Introduccion al aprendizaje automatico.odp -------------------------------------------------------------------------------- /Presentaciones auxiliares/4- Aprendizaje No supervisado - Introduccion al aprendizaje automatico.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sergarb1/TallerAprendizajeAutomaticoPython/834c2e8b3e1b9cf26d72fe552232e016dd842902/Presentaciones auxiliares/4- Aprendizaje No supervisado - Introduccion al aprendizaje automatico.pdf -------------------------------------------------------------------------------- /Presentaciones auxiliares/5- Aprendizaje No supervisado CASO ESTUDIO- Introduccion al aprendizaje automatico.odp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sergarb1/TallerAprendizajeAutomaticoPython/834c2e8b3e1b9cf26d72fe552232e016dd842902/Presentaciones auxiliares/5- Aprendizaje No supervisado CASO ESTUDIO- Introduccion al aprendizaje automatico.odp -------------------------------------------------------------------------------- /Presentaciones auxiliares/5- Aprendizaje No supervisado CASO ESTUDIO- Introduccion al aprendizaje automatico.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sergarb1/TallerAprendizajeAutomaticoPython/834c2e8b3e1b9cf26d72fe552232e016dd842902/Presentaciones auxiliares/5- Aprendizaje No supervisado CASO ESTUDIO- Introduccion al aprendizaje automatico.pdf -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Taller Aprendizaje Automatico (Machine Learning) 2 | Taller de iniciación al aprendizaje automático usando Python 3 y biblioteca scikit-learn 3 | 4 | En el taller se trata de forma introductora: 5 | * Aprendizaje supervisado (Clasificación y Regresión). 6 | * Aprendizaje no supervisado. 7 | 8 | Incluye presentación completa en formato ODP y PDF, así como ejemplos en Python 3. 9 | 10 | # Videos del taller 11 | Enlace a la playlist completa: https://www.youtube.com/playlist?list=PLhXgMPWSWXccjsM-80XpgRAjIs6b1SHqm 12 | 13 | * Parte 0: Introducción https://youtu.be/KoO3eDdffXg 14 | * Parte 1: Conceptos previos https://youtu.be/TwUzeFyZP6c 15 | * Parte 2: Aprendizaje supervisado https://youtu.be/2zByIEqLdqc 16 | * Parte 3: Aprendizaje superisado. Caso de estudio https://youtu.be/4IIrWp_JeSQ 17 | * Parte 4: Aprendizaje no supervisado. https://youtu.be/RDEXvyMGF9o 18 | * Parte 5: Aprendizaje no supervisado. Caso de estudio https://youtu.be/S_0pECnU6xw 19 | -------------------------------------------------------------------------------- /Supervisado/Clasificacion/3EnRayaConScore/3EnRayaJuego.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #Biblioteca para clasificador arbol 3 | from sklearn import tree 4 | #Biblioteca para funciones del tiempo 5 | import time 6 | #Biblioteca para importar/exportar el modelo entrenado 7 | import joblib 8 | #Biblioteca generar números aleatorios 9 | import random 10 | #Biblioteca para realizar operaciones de sistema 11 | import sys 12 | 13 | 14 | #Funcion que recibe un tablero y lo pinta 15 | def pintarTablero(tab): 16 | print("------------------------------------------") 17 | for i in range(3): 18 | cad=" | " +str(tab[0+(i*3)])+ " | "+str(tab[1+(i*3)])+ " | "+str(tab[2+(i*3)])+ " | " 19 | cad=cad.replace("0","-") 20 | cad=cad.replace("1","X") 21 | cad=cad.replace("2","O") 22 | 23 | print (cad) 24 | 25 | print("------------------------------------------") 26 | 27 | # Funcion que recibe un tablero y devuelve true si ha ganado, false en caso contrario 28 | def haGanado(tab): 29 | if(tab[0]!=0 and tab[0] == tab[1] and tab[1] == tab[2]): 30 | return True 31 | if(tab[3]!=0 and tab[3] == tab[4] and tab[4] == tab[5]): 32 | return True 33 | if(tab[6]!=0 and tab[6] == tab[7] and tab[7] == tab[8]): 34 | return True 35 | 36 | if(tab[0]!=0 and tab[0] == tab[3] and tab[3] == tab[6]): 37 | return True 38 | if(tab[1]!=0 and tab[1] == tab[4] and tab[4] == tab[7]): 39 | return True 40 | if(tab[2]!=0 and tab[2] == tab[5] and tab[5] == tab[8]): 41 | return True 42 | 43 | if(tab[0]!=0 and tab[0] == tab[4] and tab[4] == tab[8]): 44 | return True 45 | if(tab[2]!=0 and tab[2] == tab[4] and tab[4] == tab[6]): 46 | return True 47 | 48 | return False 49 | 50 | 51 | #Funcion que juega la maquina y se le pasa que turno es 52 | def jugarMaquina(turno): 53 | 54 | #Indicamos que es -1 como que no ha habido movimiento registrado 55 | movimiento=-1 56 | #Ponemos mejor a -1 57 | mejor=-1.0 58 | print("Muestras") 59 | 60 | 61 | #Se prueban las casillas del 0 al 8 62 | for i in range(9): 63 | #Si la posicion esta libre 64 | if tablero[i]==0: 65 | #Si no ha habido ningun movimiento, cogemos ese "por defecto" 66 | if movimiento==-1: 67 | movimiento=i 68 | #Generamos la muestra, con el estado del tablero, la posicion a la que movemos y el turno actual 69 | muestra=tablero + [i] + [turno] 70 | 71 | pred=classif.predict_proba([muestra]) 72 | 73 | #Sumar aleatoriedad 74 | #pred[0][1]=pred[0][1]+random.uniform(0.0,0.05) 75 | 76 | if(pred[0][1]>mejor): 77 | mejor=pred[0][1] 78 | movimiento=i 79 | 80 | tablero[movimiento]=turno 81 | print("Mueve la maquina a "+str(movimiento)) 82 | return 83 | 84 | #Funcion que juega un humano y se le pasa que turno es 85 | def jugarHumano(turno): 86 | print("Elige posicion") 87 | num=int(input('')) 88 | while(num<0 or num>8 or tablero[num]!=0): 89 | print("Elige posicion de nuevo:") 90 | num=int(input('')) 91 | 92 | tablero[num]=turno 93 | return 94 | 95 | #MAIN 96 | 97 | #Si hay un segundo argumento, lo tomamos como el modelo a importar 98 | if len(sys.argv)==2: 99 | numPart=int(sys.argv[1]) 100 | else: 101 | #Si no se pone, elegimos 1000 por defecto 102 | numPart=1000 103 | 104 | 105 | #Cargamos el clasificador 106 | classif = joblib.load('modelTree3EnRaya'+str(numPart)+'.pkl') 107 | 108 | print("Partida con modelo entrenado de "+str(numPart)+" partidas") 109 | 110 | #Incializacion de tablero 111 | tablero=[0,0,0,0,0,0,0,0,0] 112 | #Control del numero de jugadas 113 | nTurnos=0; 114 | #Eleccion de jugador 1 115 | print("Player 1") 116 | print("1 para jugador Humano, 2 para CPU") 117 | num=int(input('')) 118 | 119 | #Asignamos si es humano o CPU 120 | if(num==2): 121 | player1="CPU" 122 | else: 123 | player1="HUMANO" 124 | 125 | 126 | #Eleccion de jugador 2 127 | print("Player 2") 128 | print("1 para jugador Humano, 2 para CPU") 129 | num=int(input('')) 130 | 131 | #Asignamos si es humano o CPU 132 | if(num==2): 133 | player2="CPU" 134 | else: 135 | player2="HUMANO" 136 | 137 | #Pintamos el tablero antes de empezar la partida 138 | pintarTablero(tablero) 139 | 140 | #Mientras no haya un ganador, jugamos 141 | while not haGanado(tablero): 142 | #Pintamos tablero 143 | print("Esperando movimiento Player1") 144 | #Esperamos 2 segundos para "DAR TENSION" :P 145 | time.sleep(3) 146 | if(player1=="CPU"): 147 | # Juega la maquina, con turno 1 148 | jugarMaquina(1); 149 | pintarTablero(tablero) 150 | if(haGanado(tablero)): 151 | print("Ganador maquina Player 1") 152 | exit() 153 | else: 154 | #Juega humano con turno 1 155 | jugarHumano(1) 156 | pintarTablero(tablero) 157 | if(haGanado(tablero)): 158 | print("Ganador humano Player 1") 159 | exit() 160 | 161 | 162 | 163 | #Sumaamos un turno 164 | nTurnos=nTurnos+1 165 | 166 | #Caso empate por turnos agotados 167 | if(nTurnos==9): 168 | print("Empate") 169 | exit() 170 | 171 | print("Esperando movimiento Player2") 172 | time.sleep(3) 173 | 174 | if(player2=="CPU"): 175 | # Juega la maquina, con turno 2 176 | jugarMaquina(2); 177 | pintarTablero(tablero) 178 | if(haGanado(tablero)): 179 | print("Ganador maquina Player 2") 180 | exit() 181 | 182 | else: 183 | # Juega humano, con turno 2 184 | jugarHumano(2) 185 | pintarTablero(tablero) 186 | if(haGanado(tablero)): 187 | print("Ganador humano Player 2") 188 | exit() 189 | 190 | nTurnos=nTurnos+1 191 | #Caso empate por turnos agotados 192 | if(nTurnos==9): 193 | print("Empate") 194 | exit() 195 | 196 | 197 | -------------------------------------------------------------------------------- /Supervisado/Clasificacion/3EnRayaConScore/EntrenarModeloTree.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | #Biblioteca para usar JSON 4 | import json 5 | #Biblioteca para modelos tipo "arbol" 6 | from sklearn import tree 7 | #Biblioteca para importar/exportar modelo entrenado 8 | import joblib 9 | #Biblioteca para realizar operaciones de sistema 10 | import sys 11 | 12 | #MAIN 13 | #Si hay un segundo argumento, lo tomamos como el numero del JSON a leer (y modelo a entrenar) 14 | if len(sys.argv)==2: 15 | numPart=int(sys.argv[1]) 16 | #Si no ponemos valor por defecto, tomamos valor 1000 17 | else: 18 | numPart=1000 19 | 20 | print("Entrenando Arbol con modelo de "+str(numPart)+" partidas") 21 | 22 | #Cargamos el JSON de las partidas generadas 23 | with open('../data'+str(numPart)+'.json') as file: 24 | data = json.load(file) 25 | 26 | 27 | #En base a las partidas, creamos una lista de las features que queremos para cada ejemplo 28 | # Ahi metemos los elementos de la partida del 0 al 10 29 | features=[] 30 | for i in range(len(data)): 31 | features.append(data[i][:11]) 32 | #En base a cada partida, creamos una etiqueta con el valor almacenado en la posicion 11 33 | #0 Derrota, 1 Victoria 34 | labels=[] 35 | for i in range(len(data)): 36 | labels.append(data[i][11]) 37 | 38 | #Creamos clasificador basado en arbol de decision https://en.wikipedia.org/wiki/Decision_tree_learning 39 | classif = tree.DecisionTreeClassifier() 40 | #Entrenamos el clasificador 41 | classif.fit(features, labels) 42 | 43 | #Salvamos el modelo entrenado 44 | joblib.dump(classif, 'modelTree3EnRaya'+str(numPart)+'.pkl') 45 | 46 | print('Salvamos el modelo en :modelTree3EnRaya'+str(numPart)+'.pkl') 47 | 48 | 49 | #Comentado, para probar rapido el clasificador, la probabilidad y imprimir el arbol 50 | # print (classif.predict([[0, 0, 0, 0, 0, 0, 0, 1, 0, 4, 1]])) 51 | # print (classif.predict_proba([[0, 0, 0, 0, 0, 0, 0, 1, 0, 4, 1]])) 52 | # Para obtener el arbol asociado 53 | #textoTree = tree.export_text(classif) 54 | #print(textoTree) 55 | -------------------------------------------------------------------------------- /Supervisado/Clasificacion/3EnRayaConScore/modelTree3EnRaya.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sergarb1/TallerAprendizajeAutomaticoPython/834c2e8b3e1b9cf26d72fe552232e016dd842902/Supervisado/Clasificacion/3EnRayaConScore/modelTree3EnRaya.pkl -------------------------------------------------------------------------------- /Supervisado/Clasificacion/3EnRayaConScore/modelTree3EnRaya1000.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sergarb1/TallerAprendizajeAutomaticoPython/834c2e8b3e1b9cf26d72fe552232e016dd842902/Supervisado/Clasificacion/3EnRayaConScore/modelTree3EnRaya1000.pkl -------------------------------------------------------------------------------- /Supervisado/Clasificacion/3EnRayaConScore/modelTree3EnRaya2.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sergarb1/TallerAprendizajeAutomaticoPython/834c2e8b3e1b9cf26d72fe552232e016dd842902/Supervisado/Clasificacion/3EnRayaConScore/modelTree3EnRaya2.pkl -------------------------------------------------------------------------------- /Supervisado/Clasificacion/3EnRayaConScore/modelTree3EnRaya20000.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sergarb1/TallerAprendizajeAutomaticoPython/834c2e8b3e1b9cf26d72fe552232e016dd842902/Supervisado/Clasificacion/3EnRayaConScore/modelTree3EnRaya20000.pkl -------------------------------------------------------------------------------- /Supervisado/Clasificacion/3EnRayaConScore/modelTree3EnRaya50000.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sergarb1/TallerAprendizajeAutomaticoPython/834c2e8b3e1b9cf26d72fe552232e016dd842902/Supervisado/Clasificacion/3EnRayaConScore/modelTree3EnRaya50000.pkl -------------------------------------------------------------------------------- /Supervisado/Clasificacion/3EnRayaSinScore/3EnRayaJuegoSinScore.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | #Biblioteca para clasificador arbol 4 | from sklearn import tree 5 | #Biblioteca para funciones del tiempo 6 | import time 7 | #Biblioteca para importar/exportar el modelo entrenado 8 | import joblib 9 | #Biblioteca generar números aleatorios 10 | import random 11 | #Biblioteca para realizar operaciones de sistema 12 | import sys 13 | 14 | 15 | #Funcion que recibe un tablero y lo pinta 16 | def pintarTablero(tab): 17 | print("------------------------------------------") 18 | for i in range(3): 19 | cad=" | " +str(tab[0+(i*3)])+ " | "+str(tab[1+(i*3)])+ " | "+str(tab[2+(i*3)])+ " | " 20 | cad=cad.replace("0","-") 21 | cad=cad.replace("1","X") 22 | cad=cad.replace("2","O") 23 | 24 | print (cad) 25 | 26 | print("------------------------------------------") 27 | 28 | # Funcion que recibe un tablero y devuelve true si ha ganado, false en caso contrario 29 | def haGanado(tab): 30 | if(tab[0]!=0 and tab[0] == tab[1] and tab[1] == tab[2]): 31 | return True 32 | if(tab[3]!=0 and tab[3] == tab[4] and tab[4] == tab[5]): 33 | return True 34 | if(tab[6]!=0 and tab[6] == tab[7] and tab[7] == tab[8]): 35 | return True 36 | 37 | if(tab[0]!=0 and tab[0] == tab[3] and tab[3] == tab[6]): 38 | return True 39 | if(tab[1]!=0 and tab[1] == tab[4] and tab[4] == tab[7]): 40 | return True 41 | if(tab[2]!=0 and tab[2] == tab[5] and tab[5] == tab[8]): 42 | return True 43 | 44 | if(tab[0]!=0 and tab[0] == tab[4] and tab[4] == tab[8]): 45 | return True 46 | if(tab[2]!=0 and tab[2] == tab[4] and tab[4] == tab[6]): 47 | return True 48 | 49 | return False 50 | 51 | 52 | #Funcion que juega la maquina y se le pasa que turno es 53 | def jugarMaquina(turno): 54 | 55 | movimiento=-1 56 | #Lista en que se guardaran las candidatas. Estas son las que estan clasificadas como que fueron 57 | #jugadas victoriosas 58 | candidatas=[] 59 | for i in range(9): 60 | if tablero[i]==0: 61 | #Si no ha habido ningun movimiento, el que sea 62 | if movimiento==-1: 63 | movimiento=i 64 | 65 | #Generamos la muestra, con el estado del tablero, la posicion a la que movemos y el turno actual 66 | muestra=tablero + [i] + [turno] 67 | #Predecimos si la muestra es ganadora o no 68 | pred=classif.predict([muestra]) 69 | #Si se predice como correcta, se anyade a candidatas 70 | if(pred[0]==1): 71 | candidatas.append(i) 72 | #Si hay candidatas, elijo una al azar 73 | if(len(candidatas)>0): 74 | movimiento=candidatas[random.randint(0,len(candidatas)-1)] 75 | 76 | tablero[movimiento]=turno 77 | print("Mueve la maquina a "+str(movimiento)) 78 | return 79 | 80 | #Funcion que juega un humano y se le pasa que turno es 81 | def jugarHumano(turno): 82 | print("Elige posicion") 83 | num=int(input('')) 84 | while(num<0 or num>8 or tablero[num]!=0): 85 | print("Elige posicion de nuevo:") 86 | num=int(input('')) 87 | 88 | tablero[num]=turno 89 | return 90 | 91 | 92 | 93 | #MAIN 94 | 95 | #Si hay un segundo argumento, lo tomamos como el modelo a importar 96 | if len(sys.argv)==2: 97 | numPart=int(sys.argv[1]) 98 | else: 99 | #Si no se pone, elegimos 1000 por defecto 100 | numPart=1000 101 | 102 | 103 | #Cargamos el clasificador 104 | classif = joblib.load('modelTree3EnRaya'+str(numPart)+'.pkl') 105 | 106 | print("Partida con modelo entrenado de "+str(numPart)+" partidas") 107 | 108 | #Incializacion de tablero 109 | tablero=[0,0,0,0,0,0,0,0,0] 110 | #Control del numero de jugadas 111 | nTurnos=0; 112 | #Eleccion de jugador 1 113 | print("Player 1") 114 | print("1 para jugador Humano, 2 para CPU") 115 | num=int(input('')) 116 | 117 | #Asignamos si es humano o CPU 118 | if(num==2): 119 | player1="CPU" 120 | else: 121 | player1="HUMANO" 122 | 123 | 124 | #Eleccion de jugador 2 125 | print("Player 2") 126 | print("1 para jugador Humano, 2 para CPU") 127 | num=int(input('')) 128 | 129 | #Asignamos si es humano o CPU 130 | if(num==2): 131 | player2="CPU" 132 | else: 133 | player2="HUMANO" 134 | 135 | 136 | #Pintamos el tablero antes de empezar la partida 137 | pintarTablero(tablero) 138 | 139 | #Mientras no haya un ganador, jugamos 140 | while not haGanado(tablero): 141 | print("Esperando movimiento Player1") 142 | #Esperamos 2 segundos para "DAR TENSION" :P 143 | time.sleep(3) 144 | 145 | if(player1=="CPU"): 146 | # Juega la maquina, con turno 1 147 | jugarMaquina(1); 148 | pintarTablero(tablero) 149 | if(haGanado(tablero)): 150 | print("Ganador maquina Player 1") 151 | exit() 152 | else: 153 | #Juega humano con turno 1 154 | jugarHumano(1) 155 | pintarTablero(tablero) 156 | if(haGanado(tablero)): 157 | print("Ganador humano Player 1") 158 | exit() 159 | 160 | 161 | #Sumaamos un turno 162 | nTurnos=nTurnos+1 163 | 164 | #Caso empate por turnos agotados 165 | if(nTurnos==9): 166 | print("Empate") 167 | exit() 168 | 169 | print("Esperando movimiento Player2") 170 | time.sleep(3) 171 | 172 | if(player2=="CPU"): 173 | # Juega la maquina, con turno 2 174 | jugarMaquina(2); 175 | pintarTablero(tablero) 176 | if(haGanado(tablero)): 177 | print("Ganador maquina Player 2") 178 | exit() 179 | 180 | else: 181 | # Juega humano, con turno 2 182 | jugarHumano(2) 183 | pintarTablero(tablero) 184 | if(haGanado(tablero)): 185 | print("Ganador humano Player 2") 186 | exit() 187 | 188 | nTurnos=nTurnos+1 189 | #Caso empate por turnos agotados 190 | if(nTurnos==9): 191 | print("Empate") 192 | exit() 193 | 194 | 195 | -------------------------------------------------------------------------------- /Supervisado/Clasificacion/3EnRayaSinScore/EntrenarModeloSVM.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #Biblioteca para usar JSON 3 | import json 4 | #Biblioteca para usar "Maquinas de vector de soportel" 5 | from sklearn import svm 6 | 7 | # Biblioteca para importar/exportar el modelo entrenado 8 | import joblib 9 | 10 | #Biblioteca para usar funciones del sistema 11 | import sys 12 | 13 | #MAIN 14 | #Si hay un segundo argumento, lo tomamos como el numero del JSON a leer (y modelo a entrenar) 15 | if len(sys.argv)==2: 16 | numPart=int(sys.argv[1]) 17 | #Si no ponemos valor por defecto, tomamos valor 1000 18 | else: 19 | numPart=1000 20 | 21 | print("Entrenando SVM con modelo de "+str(numPart)+" partidas") 22 | 23 | #Cargamos el JSON de las partidas generadas 24 | with open('../data'+str(numPart)+'.json') as file: 25 | data = json.load(file) 26 | 27 | #En base a las partidas, creamos una lista de las features que queremos para cada ejemplo 28 | # Ahi metemos los elementos de la partida del 0 al 10 29 | features=[] 30 | for i in range(len(data)): 31 | features.append(data[i][:11]) 32 | 33 | 34 | #En base a cada partida, creamos una etiqueta con el valor almacenado en la posicion 11 35 | #0 Derrota, 1 Victoria 36 | labels=[] 37 | for i in range(len(data)): 38 | labels.append(data[i][11]) 39 | 40 | # Creamos clasificador de maquina de vectores de soporte https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html 41 | # Maquinas de vectores de soporte https://es.wikipedia.org/wiki/M%C3%A1quinas_de_vectores_de_soporte 42 | classif = svm.SVC(gamma=0.001, C=100.) 43 | classif.fit(features, labels) 44 | #Salvamos el modelo entrenado 45 | joblib.dump(classif, 'modelTree3EnRaya'+str(numPart)+'.pkl') 46 | 47 | #Para probar rapido la clasificacion 48 | #print (classif.predict([[0, 0, 0, 0, 0, 0, 0, 1, 0, 4, 1]])) 49 | 50 | -------------------------------------------------------------------------------- /Supervisado/Clasificacion/3EnRayaSinScore/modelTree3EnRaya1000.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sergarb1/TallerAprendizajeAutomaticoPython/834c2e8b3e1b9cf26d72fe552232e016dd842902/Supervisado/Clasificacion/3EnRayaSinScore/modelTree3EnRaya1000.pkl -------------------------------------------------------------------------------- /Supervisado/Clasificacion/3EnRayaSinScore/modelTree3EnRaya2.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sergarb1/TallerAprendizajeAutomaticoPython/834c2e8b3e1b9cf26d72fe552232e016dd842902/Supervisado/Clasificacion/3EnRayaSinScore/modelTree3EnRaya2.pkl -------------------------------------------------------------------------------- /Supervisado/Clasificacion/GenerarPartidas3EnRaya.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | # Incluimos la biblioteca para trabajar con aleatorios 4 | import random 5 | #Incluimos biblioteca para trabaja con JSON 6 | import json 7 | 8 | # Funcion que recibe un tablero y devuelve true si ha ganado, false en caso contrario 9 | def haGanado(tab): 10 | if(tab[0]!=0 and tab[0] == tab[1] and tab[1] == tab[2]): 11 | return True 12 | if(tab[3]!=0 and tab[3] == tab[4] and tab[4] == tab[5]): 13 | return True 14 | if(tab[6]!=0 and tab[6] == tab[7] and tab[7] == tab[8]): 15 | return True 16 | 17 | if(tab[0]!=0 and tab[0] == tab[3] and tab[3] == tab[6]): 18 | return True 19 | if(tab[1]!=0 and tab[1] == tab[4] and tab[4] == tab[7]): 20 | return True 21 | if(tab[2]!=0 and tab[2] == tab[5] and tab[5] == tab[8]): 22 | return True 23 | 24 | if(tab[0]!=0 and tab[0] == tab[4] and tab[4] == tab[8]): 25 | return True 26 | if(tab[2]!=0 and tab[2] == tab[4] and tab[4] == tab[6]): 27 | return True 28 | 29 | return False 30 | 31 | 32 | # funcion que juega una partida aleatoria y guarda todas las jugadas 33 | # Al finalizar, etiqueta las jugadas con quien ha ganado o perdido la partida 34 | # o a los dos como perdedores si hay empate 35 | # Devuelve las jugadas realizadas etiquetadas 36 | def partidaAleatoria(): 37 | # Definimos tablero inicial 38 | tablero = [0, 0, 0, 0, 0, 0, 0, 0, 0] 39 | # Definimos turno inicial aleatoriamente 40 | turno = random.randint(1,2) 41 | # Definimos jugadas realizadas 42 | jugadas = 0 43 | 44 | # historico de jugadas, vacio, con dos listas 45 | historico = [[], []] 46 | 47 | while jugadas < 9: 48 | 49 | # obtenemos posicion y si esta ocupada repetimos 50 | posicion = random.randint(0, 8) 51 | while tablero[posicion] != 0: 52 | posicion = random.randint(0, 8) 53 | # Anotamos una jugada mas 54 | jugadas = jugadas+1 55 | 56 | # Almacenamos el historico, estado del tablero y a donde mueve 57 | muestra=tablero[:] + [posicion] +[turno] 58 | 59 | historico[turno-1].append(muestra) 60 | # Cambiamos el tablero 61 | tablero[posicion] = turno 62 | 63 | 64 | # Si la partida ha acabado en victoria 65 | if(haGanado(tablero)): 66 | # Marcamos como ganadores 67 | for i in range(len(historico[turno-1])): 68 | historico[turno-1][i].append(1) 69 | # Cambiamos turno 70 | if turno == 1: 71 | turno = 2 72 | else: 73 | turno = 1 74 | # Marcamos como perdedores 75 | for i in range(len(historico[turno-1])): 76 | historico[turno-1][i].append(0) 77 | 78 | res = historico[0] + historico[1] 79 | return res 80 | 81 | # Cambiamos turno 82 | if turno == 1: 83 | turno = 2 84 | else: 85 | turno = 1 86 | 87 | # Si llegamos aqui, hubo un empate y damos a los dos jugadores como perdedores 88 | for i in range(len(historico[0])): 89 | historico[0][i].append(0) 90 | for i in range(len(historico[1])): 91 | historico[1][i].append(0) 92 | res = historico[0] + historico[1] 93 | 94 | return res 95 | 96 | 97 | # Aqui el main 98 | 99 | #Definimos cuantas partidas vamos a jugar 100 | nPartidas=1 101 | data=[] 102 | #Jugamos las partidas 103 | for i in range (nPartidas): 104 | #Imprimmos el progreso cada 1000 partidas 105 | if i>=1000 and i%1000==0: 106 | print(i) 107 | #Anyadimos el valor de la partida aleatoria 108 | data = data + partidaAleatoria() 109 | 110 | #Guardamos las partidas generadas en el fichero JSON 111 | with open('data'+str(nPartidas)+'.json', 'w') as outfile: 112 | json.dump(data, outfile) 113 | 114 | print("Se han jugado "+str(nPartidas)+" y se han guardado data"+str(nPartidas)+".json") -------------------------------------------------------------------------------- /Supervisado/Clasificacion/data1.json: -------------------------------------------------------------------------------- 1 | [[0, 0, 0, 0, 2, 0, 0, 0, 0, 3, 1, 0], [0, 0, 0, 1, 2, 0, 0, 0, 2, 5, 1, 0], [0, 2, 0, 1, 2, 1, 0, 0, 2, 2, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 2, 1], [0, 0, 0, 1, 2, 0, 0, 0, 0, 8, 2, 1], [0, 0, 0, 1, 2, 1, 0, 0, 2, 1, 2, 1], [0, 2, 1, 1, 2, 1, 0, 0, 2, 7, 2, 1]] -------------------------------------------------------------------------------- /Supervisado/Clasificacion/data2.json: -------------------------------------------------------------------------------- 1 | [[0, 0, 2, 0, 0, 0, 0, 0, 0, 7, 1, 0], [0, 0, 2, 0, 0, 2, 0, 1, 0, 6, 1, 0], [0, 2, 2, 0, 0, 2, 1, 1, 0, 4, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 1], [0, 0, 2, 0, 0, 0, 0, 1, 0, 5, 2, 1], [0, 0, 2, 0, 0, 2, 1, 1, 0, 1, 2, 1], [0, 2, 2, 0, 1, 2, 1, 1, 0, 8, 2, 1], [2, 0, 0, 0, 0, 0, 0, 0, 0, 7, 1, 0], [2, 0, 2, 0, 0, 0, 0, 1, 0, 8, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1], [2, 0, 0, 0, 0, 0, 0, 1, 0, 2, 2, 1], [2, 0, 2, 0, 0, 0, 0, 1, 1, 1, 2, 1]] -------------------------------------------------------------------------------- /Supervisado/Regresion/ConsultarPrecioPiso.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #incluiamos de sklearn modelos lineal 3 | from sklearn import linear_model 4 | #Biblioteca para usar JSON 5 | import json 6 | # Biblioteca para importar/exportar el modelo entrenado 7 | import joblib 8 | 9 | 10 | #Cargamos el modelo de regresion lineal 11 | lr = joblib.load('modeloRegresion.pkl') 12 | 13 | while(True): 14 | print("Introduzca los metros de su piso:") 15 | metros=int(input()) 16 | precioPred = lr.predict([[metros]]) 17 | print("Su piso esta valorado en "+str(int(precioPred[0][0]))+ " Euros") 18 | -------------------------------------------------------------------------------- /Supervisado/Regresion/RegresionPisos.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | #incluiamos de sklearn modelos lineal 4 | from sklearn import linear_model 5 | #Biblioteca para usar JSON 6 | import json 7 | # Biblioteca para importar/exportar el modelo entrenado 8 | import joblib 9 | 10 | 11 | #Ejemplos de entrenamiento 12 | # Caracteristicas (metrosPiso) 13 | metrosPisos=[[50],[100],[120],[150],[400],[95],[90]] 14 | # Valores asociados (precioPiso) 15 | precioPisos=[[30000],[120000],[140000],[150000],[300000],[100000],[110000]] 16 | 17 | 18 | #Utilizamos LinearRegression, que es regresion lineal por mínimos cuadrados 19 | #https://sites.google.com/site/numerictron/unidad-4/4-3-regresion-por-minimos-cuadrados-lineal-y-cuadratica 20 | lr = linear_model.LinearRegression() 21 | 22 | #Entrenamos el modelo de regresion linea 23 | lr.fit(metrosPisos,precioPisos) 24 | 25 | #Salvamos el modelo entrenado 26 | joblib.dump(lr, 'modeloRegresion.pkl') 27 | 28 | #Probamos con rangos desde 50 a 200 de 10 en 10 e intentamos predecir precio 29 | for i in range(50,200,10): 30 | print("Piso de "+str(i)+" metros") 31 | print("Predecimos precio:") 32 | precioPred = lr.predict([[i]]) 33 | print(str(int(precioPred[0][0]))+ " Euros") 34 | 35 | -------------------------------------------------------------------------------- /Supervisado/Regresion/modeloRegresion.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sergarb1/TallerAprendizajeAutomaticoPython/834c2e8b3e1b9cf26d72fe552232e016dd842902/Supervisado/Regresion/modeloRegresion.pkl -------------------------------------------------------------------------------- /Taller - Introduccion al aprendizaje automatico (Supervisado y no supervisado).odp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sergarb1/TallerAprendizajeAutomaticoPython/834c2e8b3e1b9cf26d72fe552232e016dd842902/Taller - Introduccion al aprendizaje automatico (Supervisado y no supervisado).odp -------------------------------------------------------------------------------- /Taller - Introduccion al aprendizaje automatico (Supervisado y no supervisado).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sergarb1/TallerAprendizajeAutomaticoPython/834c2e8b3e1b9cf26d72fe552232e016dd842902/Taller - Introduccion al aprendizaje automatico (Supervisado y no supervisado).pdf --------------------------------------------------------------------------------