-
Notifications
You must be signed in to change notification settings - Fork 283
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Ficheros 'my_xxx' creados durante el curso como parte de los ejercicios de las lecciones
- Loading branch information
Showing
16 changed files
with
706 additions
and
0 deletions.
There are no files selected for viewing
Binary file not shown.
Binary file modified
BIN
+0 Bytes
(100%)
datasets/Get the Machine Learning Basics/Classification Template/.DS_Store
Binary file not shown.
83 changes: 83 additions & 0 deletions
83
...ne Learning Basics/Classification Template/Classification Template/logistic_regression.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,83 @@ | ||
#!/usr/bin/env python3 | ||
# -*- coding: utf-8 -*- | ||
""" | ||
Created on Wed Feb 5 18:37:58 2020 | ||
@author: ramonpuga | ||
""" | ||
|
||
# Regresion Logística | ||
|
||
# Importar las librerias | ||
import numpy as np | ||
import matplotlib.pyplot as plt | ||
import pandas as pd | ||
|
||
# Importar el dataset | ||
dataset = pd.read_csv('Social_Network_Ads.csv') | ||
|
||
# Matriz X con todas las filas, y todas las columnas menos la última | ||
X = dataset.iloc[:, [2,3]].values | ||
# Vector y con todas las filas y la última columna | ||
y = dataset.iloc[:, -1].values | ||
|
||
# Dividir el data set en conjunto de training y de test | ||
from sklearn.model_selection import train_test_split | ||
# Aplicamos un porcentaje del 25% (0.25) para el test y un valor de selección alatoria de 0 | ||
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0) | ||
|
||
# Escalado (estandarización o normalización) de variables | ||
from sklearn.preprocessing import StandardScaler | ||
sc_X = StandardScaler() | ||
# Aplicamos y fijamos el metodo de estandarización a todas las columnas X | ||
X_train = sc_X.fit_transform(X_train) | ||
# Aplicamos el mismo metodo de estandarización que para los datos de Training | ||
X_test = sc_X.transform(X_test) | ||
|
||
# Ajustar el modelo de Regresión Logística en el Conjunto de Training | ||
from sklearn.linear_model import LogisticRegression | ||
classifier = LogisticRegression(random_state = 0) | ||
classifier.fit(X_train, y_train) | ||
|
||
# Predicción de los resultados con el conjunto de Testing | ||
y_pred = classifier.predict(X_test) | ||
|
||
# Elaborar una matriz de confusión | ||
from sklearn.metrics import confusion_matrix | ||
cm = confusion_matrix(y_test, y_pred) | ||
|
||
# Representación gráfica de los resultados del algoritmo | ||
from matplotlib.colors import ListedColormap | ||
X_set, y_set = X_train, y_train | ||
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01), | ||
np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01)) | ||
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), | ||
alpha = 0.75, cmap = ListedColormap(('red', 'green'))) | ||
plt.xlim(X1.min(), X1.max()) | ||
plt.ylim(X2.min(), X2.max()) | ||
for i, j in enumerate(np.unique(y_set)): | ||
plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1], | ||
c = ListedColormap(('red', 'green'))(i), label = j) | ||
plt.title('Clasificador (Conjunto de Training)') | ||
plt.xlabel('Edad') | ||
plt.ylabel('Sueldo Estimado') | ||
plt.legend() | ||
plt.show() | ||
|
||
# Representación gráfica de los resultados del algoritmo | ||
from matplotlib.colors import ListedColormap | ||
X_set, y_set = X_test, y_test | ||
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01), | ||
np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01)) | ||
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), | ||
alpha = 0.75, cmap = ListedColormap(('red', 'green'))) | ||
plt.xlim(X1.min(), X1.max()) | ||
plt.ylim(X2.min(), X2.max()) | ||
for i, j in enumerate(np.unique(y_set)): | ||
plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1], | ||
c = ListedColormap(('red', 'green'))(i), label = j) | ||
plt.title('Clasificador (Conjunto de Test)') | ||
plt.xlabel('Edad') | ||
plt.ylabel('Sueldo Estimado') | ||
plt.legend() | ||
plt.show() |
84 changes: 84 additions & 0 deletions
84
...ning Basics/Classification Template/Classification Template/my_classification_template.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,84 @@ | ||
#!/usr/bin/env python3 | ||
# -*- coding: utf-8 -*- | ||
""" | ||
Created on Wed Feb 5 21:13:23 2020 | ||
@author: ramonpuga | ||
""" | ||
|
||
# Plantilla de Clasificación | ||
|
||
# Importar las librerias | ||
import numpy as np | ||
import matplotlib.pyplot as plt | ||
import pandas as pd | ||
|
||
# Importar el dataset | ||
dataset = pd.read_csv('Social_Network_Ads.csv') | ||
|
||
# Matriz X con todas las filas, y todas las columnas menos la última | ||
X = dataset.iloc[:, [2,3]].values | ||
# Vector y con todas las filas y la última columna | ||
y = dataset.iloc[:, -1].values | ||
|
||
# Dividir el data set en conjunto de training y de test | ||
from sklearn.model_selection import train_test_split | ||
# Aplicamos un porcentaje del 25% (0.25) para el test y un valor de selección alatoria de 0 | ||
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0) | ||
|
||
# Escalado (estandarización o normalización) de variables | ||
from sklearn.preprocessing import StandardScaler | ||
sc_X = StandardScaler() | ||
# Aplicamos y fijamos el metodo de estandarización a todas las columnas X | ||
X_train = sc_X.fit_transform(X_train) | ||
# Aplicamos el mismo metodo de estandarización que para los datos de Training | ||
X_test = sc_X.transform(X_test) | ||
|
||
|
||
# Ajustar el clasificador en el Conjunto de Training | ||
# Crear aquí el modelo de Clasificación | ||
# classifier | ||
|
||
|
||
# Predicción de los resultados con el conjunto de Testing | ||
y_pred = classifier.predict(X_test) | ||
|
||
# Elaborar una matriz de confusión | ||
from sklearn.metrics import confusion_matrix | ||
cm = confusion_matrix(y_test, y_pred) | ||
|
||
# Representación gráfica de los resultados del algoritmo | ||
from matplotlib.colors import ListedColormap | ||
X_set, y_set = X_train, y_train | ||
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01), | ||
np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01)) | ||
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), | ||
alpha = 0.75, cmap = ListedColormap(('red', 'green'))) | ||
plt.xlim(X1.min(), X1.max()) | ||
plt.ylim(X2.min(), X2.max()) | ||
for i, j in enumerate(np.unique(y_set)): | ||
plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1], | ||
c = ListedColormap(('red', 'green'))(i), label = j) | ||
plt.title('Clasificador (Conjunto de Training)') | ||
plt.xlabel('Edad') | ||
plt.ylabel('Sueldo Estimado') | ||
plt.legend() | ||
plt.show() | ||
|
||
# Representación gráfica de los resultados del algoritmo | ||
from matplotlib.colors import ListedColormap | ||
X_set, y_set = X_test, y_test | ||
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01), | ||
np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01)) | ||
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), | ||
alpha = 0.75, cmap = ListedColormap(('red', 'green'))) | ||
plt.xlim(X1.min(), X1.max()) | ||
plt.ylim(X2.min(), X2.max()) | ||
for i, j in enumerate(np.unique(y_set)): | ||
plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1], | ||
c = ListedColormap(('red', 'green'))(i), label = j) | ||
plt.title('Clasificador (Conjunto de Test)') | ||
plt.xlabel('Edad') | ||
plt.ylabel('Sueldo Estimado') | ||
plt.legend() | ||
plt.show() |
Binary file modified
BIN
+0 Bytes
(100%)
datasets/Get the Machine Learning Basics/Data Preprocessing Template/.DS_Store
Binary file not shown.
95 changes: 95 additions & 0 deletions
95
...Machine Learning Basics/Data Preprocessing Template/Data Preprocessing Template/.Rhistory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,95 @@ | ||
print("Hello world!") | ||
dataset = read.csv('Data.csv') | ||
dataset = read.csv('Data.csv') | ||
setwd("~/Dropbox/DigitalEmpathy/Nylvam/GitHub/deeplearning-az/datasets/Get the Machine Learning Basics/Data Preprocessing Template/Data Preprocessing Template") | ||
dataset = read.csv('Data.csv') | ||
View(dataset) | ||
View(dataset) | ||
dataset$Age = ifelse(is.na(datset$Age), | ||
ave(dataset$Age, FUN = function(x) mean(x, na.rm = TRUE)), | ||
dataset$Age) | ||
dataset$Age = ifelse(is.na(dataset$Age), | ||
ave(dataset$Age, FUN = function(x) mean(x, na.rm = TRUE)), | ||
dataset$Age) | ||
dataset$Salary = ifelse(is.na(dataset$Salary), | ||
ave(dataset$Salary, FUN = function(x) mean(x, na.rm = TRUE)), | ||
dataset$Salary) | ||
# Codificar las variables categóricas | ||
dataset$Country = factor(dataset$Country, | ||
levels = c("France", "Spain", "Germnay"), | ||
labels = c(1, 2, 3)) | ||
dataset$Purchased = factor(dataset$Purchased, | ||
levels = c("No", "Yes"), | ||
labels = c(0, 1)) | ||
# Dividir los datos en conjunto de training y conjunto de test | ||
# install.packages("caTools") | ||
library(caTools) | ||
# Establecer un valor de semilla para la selección de datos | ||
set.seed(123) | ||
# Establecemos un 80% de las filas como ratio de división (training) | ||
split = sample.split(dataset$Purchased, SplitRatio = 0.8) | ||
training_set = subset(dataset, split = TRUE) | ||
testing_set = subset(dataset, split = FALSE) | ||
View(testing_set) | ||
View(training_set) | ||
View(testing_set) | ||
View(dataset) | ||
View(testing_set) | ||
View(training_set) | ||
View(dataset) | ||
dataset = read.csv('Data.csv') | ||
View(dataset) | ||
# Tratamiento de los valores NA | ||
dataset$Age = ifelse(is.na(dataset$Age), | ||
ave(dataset$Age, FUN = function(x) mean(x, na.rm = TRUE)), | ||
dataset$Age) | ||
dataset$Salary = ifelse(is.na(dataset$Salary), | ||
ave(dataset$Salary, FUN = function(x) mean(x, na.rm = TRUE)), | ||
dataset$Salary) | ||
# Codificar las variables categóricas | ||
dataset$Country = factor(dataset$Country, | ||
levels = c("France", "Spain", "Germany"), | ||
labels = c(1, 2, 3)) | ||
dataset$Purchased = factor(dataset$Purchased, | ||
levels = c("No", "Yes"), | ||
labels = c(0, 1)) | ||
# Dividir los datos en conjunto de training y conjunto de test | ||
# install.packages("caTools") | ||
library(caTools) | ||
# Establecer un valor de semilla para la selección de datos | ||
set.seed(123) | ||
# Establecemos un 80% de las filas como ratio de división (training) | ||
split = sample.split(dataset$Purchased, SplitRatio = 0.8) | ||
training_set = subset(dataset, split = TRUE) | ||
testing_set = subset(dataset, split = FALSE) | ||
View(training_set) | ||
View(testing_set) | ||
dataset = read.csv('Data.csv') | ||
View(dataset) | ||
dataset$Age = ifelse(is.na(dataset$Age), | ||
ave(dataset$Age, FUN = function(x) mean(x, na.rm = TRUE)), | ||
dataset$Age) | ||
dataset$Salary = ifelse(is.na(dataset$Salary), | ||
ave(dataset$Salary, FUN = function(x) mean(x, na.rm = TRUE)), | ||
dataset$Salary) | ||
# Codificar las variables categóricas | ||
dataset$Country = factor(dataset$Country, | ||
levels = c("France", "Spain", "Germany"), | ||
labels = c(1, 2, 3)) | ||
dataset$Purchased = factor(dataset$Purchased, | ||
levels = c("No", "Yes"), | ||
labels = c(0, 1)) | ||
library(caTools) | ||
# Establecer un valor de semilla para la selección de datos | ||
set.seed(123) | ||
split = sample.split(dataset$Purchased, SplitRatio = 0.8) | ||
training_set = subset(dataset, split == TRUE) | ||
testing_set = subset(dataset, split == FALSE) | ||
View(training_set) | ||
View(testing_set) | ||
View(dataset) | ||
training_set[,2:3] = scale(training_set[,2:3]) | ||
testing_set[,2:3] = scale(testing_set[,2:3]) | ||
View(dataset) | ||
View(training_set) | ||
View(testing_set) |
12 changes: 12 additions & 0 deletions
12
...rning Basics/Data Preprocessing Template/Data Preprocessing Template/my_categorial_data.R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
# Plantilla para el Pre Procesado de Datos - Datos Categóricos | ||
|
||
# Importar el dataset | ||
dataset = read.csv('Data.csv') | ||
|
||
# Codificar las variables categóricas | ||
dataset$Country = factor(dataset$Country, | ||
levels = c("France", "Spain", "Germany"), | ||
labels = c(1, 2, 3)) | ||
dataset$Purchased = factor(dataset$Purchased, | ||
levels = c("No", "Yes"), | ||
labels = c(0, 1)) |
55 changes: 55 additions & 0 deletions
55
...ning Basics/Data Preprocessing Template/Data Preprocessing Template/my_categorial_data.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
#!/usr/bin/env python3 | ||
# -*- coding: utf-8 -*- | ||
""" | ||
Created on Wed Feb 5 18:22:43 2020 | ||
@author: ramonpuga | ||
""" | ||
|
||
# Plantilla de Pre Procesado de Datos - Datos categóricos | ||
|
||
# Importar las librerias | ||
import numpy as np | ||
import matplotlib.pyplot as plt | ||
import pandas as pd | ||
|
||
# Importar el dataset | ||
dataset = pd.read_csv('Data.csv') | ||
# Matriz X con todas las filas, y todas las columnas menos la última | ||
X = dataset.iloc[:, :-1].values | ||
# Vector y con todas las filas y la última columna | ||
y = dataset.iloc[:, -1].values | ||
|
||
# Codificar datos de categorías | ||
from sklearn.preprocessing import LabelEncoder | ||
labelencoder_X = LabelEncoder() | ||
# La columna 0 contine valores que son categorías | ||
X[:, 0] = labelencoder_X.fit_transform(X[:, 0]) | ||
|
||
#El OneHotEncoder en las nuevas versiones está OBSOLETO | ||
|
||
# Convertimos esos valores en columnas dummy (tantas como categorías) | ||
#onehotencoder = OneHotEncoder(categorical_features=[0]) | ||
#X = onehotencoder.fit_transform(X).toarray() | ||
|
||
from sklearn.preprocessing import OneHotEncoder | ||
from sklearn.compose import ColumnTransformer | ||
|
||
transformer = ColumnTransformer( | ||
transformers=[ | ||
("Data_Modelling", # Un nombre de la transformación | ||
OneHotEncoder(categories='auto'), # La clase a la que transformar | ||
[0] # Las columnas a transformar. | ||
) | ||
], remainder='passthrough' | ||
) | ||
|
||
X = transformer.fit_transform(X) | ||
# Eliminar una columna dummy para evitar la multicolinealidad | ||
# OneHotEncoder pone las columnas dummy al principio, por lo tanto habrá que elimnar la columna 0 | ||
X = X[:, 1:] | ||
|
||
|
||
# La columna de resultados, tambien es una categória (yes or no) | ||
labelencoder_y = LabelEncoder() | ||
y = labelencoder_y.fit_transform(y) |
20 changes: 20 additions & 0 deletions
20
.../Data Preprocessing Template/Data Preprocessing Template/my_data_preprocessing_template.R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
# Plantilla para el Pre Procesado de Datos | ||
|
||
# Importar el dataset | ||
dataset = read.csv('Data.csv') | ||
# Ejemplo de seleccionar un conjunto de datos del dataset original | ||
# dataset = dataset[, 2:3] | ||
|
||
# Dividir los datos en conjunto de training y conjunto de test | ||
# install.packages("caTools") | ||
library(caTools) | ||
# Establecer un valor de semilla para la selección de datos | ||
set.seed(123) | ||
# Establecemos un 80% de las filas como ratio de división (training) | ||
split = sample.split(dataset$Purchased, SplitRatio = 0.8) | ||
training_set = subset(dataset, split == TRUE) | ||
testing_set = subset(dataset, split == FALSE) | ||
|
||
# Escalado de valores para las columnas 2 y 3 (2ª y 3ª) | ||
# training_set[,2:3] = scale(training_set[,2:3]) | ||
# testing_set[,2:3] = scale(testing_set[,2:3]) |
37 changes: 37 additions & 0 deletions
37
...Data Preprocessing Template/Data Preprocessing Template/my_data_preprocessing_template.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
#!/usr/bin/env python3 | ||
# -*- coding: utf-8 -*- | ||
""" | ||
Created on Wed Feb 5 15:15:34 2020 | ||
@author: ramonpuga | ||
""" | ||
|
||
# Plantilla de Pre Procesado de Datos | ||
|
||
# Importar las librerias | ||
import numpy as np | ||
import matplotlib.pyplot as plt | ||
import pandas as pd | ||
|
||
# Importar el dataset | ||
dataset = pd.read_csv('Data.csv') | ||
|
||
# Matriz X con todas las filas, y todas las columnas menos la última | ||
X = dataset.iloc[:, :-1].values | ||
# Vector y con todas las filas y la última columna | ||
y = dataset.iloc[:, -1].values | ||
|
||
# Dividir el data set en conjunto de training y de test | ||
from sklearn.model_selection import train_test_split | ||
# Aplicamos un porcentaje del 20% (0.2) para el test y un valor de selección alatoria de 0 | ||
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) | ||
|
||
# Escalado (estandarización o normalización) de variables | ||
""" Quitar comillas iniciales y fianles cuando se necesite este código | ||
from sklearn.preprocessing import StandardScaler | ||
sc_X = StandardScaler() | ||
# Aplicamos y fijamos el metodo de estandarización a todas las columnas X | ||
X_train = sc_X.fit_transform(X_train) | ||
# Aplicamos el mismo metodo de estandarización que para los datos de training | ||
X_test = sc_X.transform(X_test) | ||
""" |
Oops, something went wrong.