%pip install tensorflow==2.1
%matplotlib inline
# Importamos TensorFlow y Keras
import tensorflow as tf
import tensorflow.keras as keras
# Importamos el modelo Sequential
from tensorflow.keras.models import Sequential
# Importamos las capas que utilizaremos
from tensorflow.keras.layers import Dense, Dropout, Flatten, Conv1D, MaxPool1D, LSTM, GRU
# Importamos el normalizador de los datos
from sklearn.preprocessing import MinMaxScaler, StandardScaler
#importamos los optimizadores
from tensorflow.keras.optimizers import RMSprop, Adam
# Importamos el evaluador de la predicción
from sklearn.metrics import mean_absolute_error
# Importamos las librerias de análisis de datos
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import datetime, random, math
# Dependencia necesaria para descomponer las graficas y corroborar su estacionalidad.
from statsmodels.tsa.seasonal import seasonal_decompose
# Controlamos la aleatoriedad con una semilla
np.random.seed(42)
tf.random.set_seed(42)
df = pd.read_csv('data_electrica.csv')
data_electrica = df[['fecha','sistema','dmin','dmax']]
data_electrica
data_electrica.info()
# Transformaremos la columna fecha que se encuentra en formato "string" (object) a formato "fecha" (datetime)
data_electrica['fecha'] = pd.to_datetime(data_electrica['fecha'], format='%d/%m/%Y')
# Luego dejaremos nuestra columna fecha como indice del DataFrame
data_electrica = data_electrica.set_index('fecha')
# Transformaremos la columna sistema que se encuentra en formato "string" (object) a formato "categorico" (category)
data_electrica['sistema'] = data_electrica['sistema'].astype('category')
# Luego tenemos los formatos que queremos.
data_electrica.info()
# Veremos que tenemos 3 categorias en la columna sistema
data_electrica['sistema'].unique()
sns.boxplot(data = df, x = 'sistema', y='dmin')
sns.boxplot(data = df, x = 'sistema', y='dmax')
# Dividimos la data según los sitemas
data_sic = data_electrica[data_electrica['sistema'] == 'SIC']
data_sing = data_electrica[data_electrica['sistema'] == 'SING']
data_sen = data_electrica[data_electrica['sistema'] == 'SEN']
print(f'Tenemos un total de {data_sic.shape[0]} datos en el sistema SIC')
print(f'Tenemos un total de {data_sing.shape[0]} datos en el sistema SING')
print(f'Tenemos un total de {data_sen.shape[0]} datos en el sistema SEN')
print(f'El sistema SIC dispone de {data_sic.index.min()} hasta {data_sic.index.max()}')
print(f'El sistema SING dispone de {data_sing.index.min()} hasta {data_sing.index.max()}')
print(f'El sistema SEN dispone de {data_sen.index.min()} hasta {data_sen.index.max()}')
data_sic
# Graficaremos la data para poder visualizar su comportamiento (dmin)
plt.figure(figsize=(10,5))
plt.plot(data_sic['dmin'], c='r', label = 'SIC')
plt.title('Grafico sistema SIC', fontsize = 20)
plt.xlabel('años', fontsize = 18)
plt.ylabel('MW', fontsize = 18)
plt.legend(loc = 'lower right', fontsize = 14)
plt.show()
data_sic_mes = data_sic.resample('M').sum()
data_sic_mes
plt.figure(figsize=(10,5))
plt.plot(data_sic_mes['dmin'], c='r', label = 'dmin')
#plt.plot(data_sic_mes['dmean'], c='b', label = 'dmean')
plt.plot(data_sic_mes['dmax'], c = 'g', label = 'dmax')
plt.title('Grafico sistema SIC', fontsize = 20)
plt.xlabel('años', fontsize = 18)
plt.ylabel('MW', fontsize = 18)
plt.legend(loc = 'lower right', fontsize = 11)
plt.show()
fig = plt.figure(figsize=(10,10))
ax = plt.subplot(2,1,1)
ax.plot(data_sic_mes['dmin'].loc['2015'].values, label = 'dmin 2015')
ax.plot(data_sic_mes['dmin'].loc['2016'].values, label = 'dmin 2016')
ax.plot(data_sic_mes['dmin'].loc['2017'].values, label = 'dmin 2017')
plt.title('Grafico sistema SIC demanda minima', fontsize = 18)
plt.ylabel('MW', fontsize = 16)
plt.legend(loc = 'lower right', fontsize = 11)
ax = plt.subplot(2,1,2)
ax.plot(data_sic_mes['dmax'].loc['2015'].values, label = 'dmax 2015')
ax.plot(data_sic_mes['dmax'].loc['2016'].values, label = 'dmax 2016')
ax.plot(data_sic_mes['dmax'].loc['2017'].values, label = 'dmax 2017')
plt.title('Grafico sistema SIC demanda maxima', fontsize = 16)
plt.xlabel('Mes', fontsize = 16)
plt.ylabel('MW', fontsize = 16)
plt.legend(loc = 'lower right', fontsize = 11)
plt.show()
print(seasonal_decompose(data_sic_mes['dmin']).plot())
print(seasonal_decompose(data_sic_mes['dmax']).plot())
data_sing
data_sing_mes = data_sing.resample('M').sum()
data_sing_mes
plt.figure(figsize=(10,5))
plt.plot(data_sing_mes['dmin'], c='r', label = 'dmin')
plt.plot(data_sing_mes['dmax'], c = 'g', label = 'dmax')
plt.title('Grafico sistema SING', fontsize = 20)
plt.xlabel('años', fontsize = 18)
plt.ylabel('MW', fontsize = 18)
plt.legend(loc = 'lower right', fontsize = 11)
plt.show()
fig = plt.figure(figsize=(10,10))
ax = plt.subplot(2,1,1)
ax.plot(data_sing_mes['dmin'].loc['2015'].values, label = 'dmin 2015')
ax.plot(data_sing_mes['dmin'].loc['2016'].values, label = 'dmin 2016')
ax.plot(data_sing_mes['dmin'].loc['2017'].values, label = 'dmin 2017')
plt.title('Grafico sistema SING demanda minima', fontsize = 18)
plt.ylabel('MW', fontsize = 16)
plt.legend(loc = 'lower right', fontsize = 11)
ax = plt.subplot(2,1,2)
ax.plot(data_sing_mes['dmax'].loc['2015'].values, label = 'dmax 2015')
ax.plot(data_sing_mes['dmax'].loc['2016'].values, label = 'dmax 2016')
ax.plot(data_sing_mes['dmax'].loc['2017'].values, label = 'dmax 2017')
plt.title('Grafico sistema SING demanda maxima', fontsize = 16)
plt.xlabel('Mes', fontsize = 16)
plt.ylabel('MW', fontsize = 16)
plt.legend(loc = 'lower right', fontsize = 11)
plt.show()
print(seasonal_decompose(data_sing_mes['dmin']).plot())
print(seasonal_decompose(data_sing_mes['dmax']).plot())
data_sen
data_sen_mes = data_sen.resample('M').sum()
data_sen_mes.head() # Mostramos los primeros 5 meses de SEN
plt.figure(figsize=(10,5))
plt.plot(data_sen_mes['dmin'], c='r', label = 'dmin')
plt.plot(data_sen_mes['dmax'], c = 'g', label = 'dmax')
plt.title('Grafico sistema SEN', fontsize = 20)
plt.xlabel('años', fontsize = 18)
plt.ylabel('MW', fontsize = 18)
plt.legend(loc = 'lower right', fontsize = 11)
plt.show()
fig = plt.figure(figsize=(10,10))
ax = plt.subplot(2,1,1)
ax.plot(data_sen_mes['dmin'].loc['2018'].values, label = 'dmin 2018')
ax.plot(data_sen_mes['dmin'].loc['2019'].values, label = 'dmin 2019')
ax.plot(data_sen_mes['dmin'].loc['2020'].values, label = 'dmin 2020')
plt.title('Grafico sistema SEN demanda minima', fontsize = 18)
plt.ylabel('MW', fontsize = 16)
plt.legend(loc = 'lower right', fontsize = 9)
ax = plt.subplot(2,1,2)
ax.plot(data_sen_mes['dmax'].loc['2018'].values, label = 'dmax 2018')
ax.plot(data_sen_mes['dmax'].loc['2019'].values, label = 'dmax 2019')
ax.plot(data_sen_mes['dmax'].loc['2020'].values, label = 'dmax 2020')
plt.title('Grafico sistema SEN demanda maxima', fontsize = 16)
plt.xlabel('Mes', fontsize = 16)
plt.ylabel('MW', fontsize = 16)
plt.legend(loc = 'lower right', fontsize = 9)
plt.show()
print(seasonal_decompose(data_sen_mes['dmin']).plot())
print(seasonal_decompose(data_sen_mes['dmax']).plot())
def new_distribution(data, dmand: str):
rango = data[dmand].max() - data[dmand].min()
min = data[dmand].min()
Q1 = data[dmand].quantile(q=0.25)
Q2 = data[dmand].quantile(q=0.50)
Q3 = data[dmand].quantile(q=0.75)
max = data[dmand].max()
#sns.boxplot(data)
#sns.histplot(data) Por solucionar la ubicación de los graficos.
iqr = Q3 - Q1
# Pensando que que ajustamos a una distribución normal
new_min = Q1 - 1.5*iqr
new_max = Q3 + 1.5*iqr
print(f'Tenemos los datos antiguos:\nRango: {rango}\nMinimo: {min}\nQ1: {Q1}\nQ2: {Q2}\nQ3: {Q3}\nMax: {max}\nNuestro nuevo minimo sera:\nnew_min = {new_min}')
#data_sic
data_ajust= data[data[[dmand]] >= new_min ]
data_ajust = data_ajust[[dmand]]
data_ajust = data_ajust[~np.isnan(data_ajust).any(axis=1)]
sns.histplot(data_ajust)
return data_ajust
def graph_new_distribution(data_ajust, data, dmand:str):
limit = (0,6000)
if data['sistema'][0] == 'SIC':
if dmand == 'dmax':
limit = (0,8300)
else:
if dmand == 'dmin':
limit = (0,9000)
else:
limit = (6000,11500)
figura = plt.figure(figsize=(20,10))
ax = plt.subplot(1,2,1)
ax.plot(data[[dmand]])
plt.xlabel('Fecha', fontsize = 15)
plt.ylabel('Distribución Original', fontsize =15)
plt.ylim(limit)
ax = plt.subplot(1,2,2)
plt.xlabel('Fecha', fontsize = 15)
plt.ylabel('Distribución Ajustada', fontsize = 15)
ax.plot(data_ajust)
plt.ylim(limit)
plt.show()
plt.figure(figsize=(10,5))
plt.plot(data_sic[['dmin']])
plt.title('Demanda minima sistema SIC', fontsize=14)
plt.ylabel('MW', fontsize = 14)
plt.xlabel('Fecha', fontsize= 14)
plt.show()
sns.histplot(data_sic[['dmin']])
sns.boxplot(data_sic['dmin'])
sic_dmin_ajust = new_distribution(data_sic, 'dmin')
graph_new_distribution(sic_dmin_ajust, data_sic, 'dmin')
plt.figure(figsize=(10,5))
plt.plot(data_sic[['dmax']])
plt.title('Demanda máxima sistema SIC', fontsize=14)
plt.ylabel('MW', fontsize = 14)
plt.xlabel('Fecha', fontsize= 14)
plt.show()
sns.histplot(data_sic[['dmax']])
sns.boxplot(data_sic['dmax'])
sic_dmax_ajust = new_distribution(data_sic, 'dmax')
graph_new_distribution(sic_dmax_ajust, data_sic,'dmax')
plt.figure(figsize=(10,5))
plt.plot(data_sen[['dmin']])
plt.title('Demanda mínima sistema SEN', fontsize=14)
plt.ylabel('MW', fontsize = 14)
plt.xlabel('Fecha', fontsize= 14)
plt.show()
sns.histplot(data_sen['dmin'])
sns.boxplot(data_sen['dmin'])
sen_dmin_ajust = new_distribution(data_sen,'dmin')
graph_new_distribution(sen_dmin_ajust, data_sen,'dmin')
plt.figure(figsize=(10,5))
plt.plot(data_sen[['dmax']])
plt.title('Demanda máxima sistema SEN', fontsize=14)
plt.ylabel('MW', fontsize = 14)
plt.xlabel('Fecha', fontsize= 14)
plt.show()
sns.histplot(data_sen['dmax'])
sns.boxplot(data_sen['dmax'])
sen_dmax_ajust = new_distribution(data_sen,'dmax')
graph_new_distribution(sen_dmax_ajust, data_sen,'dmax')
# Seleccionamos el rango de fecha en el que miraremos hacia atras para predecir (serán 2 meses hacia atras, para predecir el siguiente mes)
end_train_sic = '2017-06'
start_test_sic = '2017-07'
end_train_sen = '2021-01'
start_test_sen = '2021-02'
# PREPARANDO LA DATA DEL SISTEMA SIC
# -----------------------------------------------------------
# Separando los datos de SIC
# --> Comenzaremos directamente a separa los datos de train (2006-01-01/2017-06-30) y test (2017-07-01...)
sic_train_dmin, sic_test_dmin = sic_dmin_ajust.loc[: end_train_sic] , sic_dmin_ajust.loc[start_test_sic:]
sic_train_dmax, sic_test_dmax = sic_dmax_ajust.loc[: end_train_sic] , sic_dmin_ajust.loc[start_test_sic:]
# Analogamente con los datos de SEN
sen_train_dmin, sen_test_dmin = sen_dmin_ajust.loc[:end_train_sen], sen_dmin_ajust.loc[start_test_sen:]
sen_train_dmax, sen_test_dmax = sen_dmax_ajust.loc[:end_train_sen], sen_dmax_ajust.loc[start_test_sen:]
sic_train_dmin.shape, sic_test_dmin.shape, sen_train_dmin.shape, sen_test_dmin.shape
############## CONFIGURACIÓN GENERAL DE LOS MODELOS ########################################################
# Seleccionamos el rango para el aprendizaje supervisado ( t-n, t-(n-1), ... , t-2, t-1, t)
PAST_HISTORY = 140
PREDICTION = 14
VAL_PERCENT = 0.20 # Valor adecuado de momento -> 0.25 (25%) | con 0.30 (malos resultados) | 0.35 "buenos graficos" | 0.10 Buenos resultados | 0.2 Excelentes resultados
# Generando el escalador de los datos.
SCALER = MinMaxScaler(feature_range=(-1,1))
# Como se entrenara el modelo
LOSS ='mean_absolute_error'
OPTIMIZER_1 = Adam(learning_rate=0.0001)
OPTIMIZER_2 = RMSprop(learning_rate=0.0001)
METRICS = ["mse"]
############# CONFIGURACIÓN MODELO SISTEMA SIC DMIN ################################################################
# Cantidad de neuronas en las capas del modelo (configurada segun la cantidad de capas)(NC = Neurona Capa)
NC_1 = 128
NC_2 = 256
NC_3 = 64
#NC_4 =
# Función de activación de las neuronas densas
ACTIVATION = 'tanh'
# Seleccionamos la cantidad de repeticiones que se entrenará (cantidad de EPOCH)
EPOCHS_1 = 50
EPOCHS_2 = 10
BATCH_SIZE = 8 # 16 y 8 (ambos buenos)
############# CONFIGURACIÓN MODELO SISTEMA SIC DMIN ################################################################
transform_data_dmin = normalize_and_supervised(sic_train_dmin)
transform_data_dmax = normalize_and_supervised(sic_train_dmax)
transform_data_dmin
pronostic_jul_dmin = data_sic[['dmin']].loc['2017-02':'2017-07']
pronostic_august_dmin = data_sic[['dmin']].loc['2017-03':'2017-08']
pronostic_sept_dmin = data_sic[['dmin']].loc['2017-04':'2017-09']
pronostic_oct_dmin = data_sic[['dmin']].loc['2017-05':'2017-10']
pronostic_nov_dmin = data_sic[['dmin']].loc['2017-06':'2017-11']
pronostic_dic_dmin = data_sic[['dmin']].loc['2017-07':'2017-12']
pronostic_jul_dmax = data_sic[['dmax']].loc['2017-02':'2017-07']
pronostic_august_dmax = data_sic[['dmax']].loc['2017-03':'2017-08']
pronostic_sept_dmax = data_sic[['dmax']].loc['2017-04':'2017-09']
pronostic_oct_dmax = data_sic[['dmax']].loc['2017-05':'2017-10']
pronostic_nov_dmax = data_sic[['dmax']].loc['2017-06':'2017-11']
pronostic_dic_dmax = data_sic[['dmax']].loc['2017-07':'2017-12']
dividing_dmin = train_and_validation(transform_data_dmin)
x_train_dmin, y_train_dmin, x_val_dmin, y_val_dmin = dividing_dmin[0], dividing_dmin[1], dividing_dmin[2], dividing_dmin[3]
dividing_dmax = train_and_validation(transform_data_dmax)
x_train_dmax, y_train_dmax, x_val_dmax, y_val_dmax = dividing_dmax[0], dividing_dmax[1], dividing_dmax[2], dividing_dmax[3]
# Mostramos la dimensiones de los tensores de entrada.
print(x_train_dmin.shape, y_train_dmin.shape, x_val_dmin.shape, y_val_dmin.shape)
def model_MLP():
model = Sequential()
model.add(Dense(NC_1, input_shape = (1, PAST_HISTORY), activation = ACTIVATION))
model.add(Flatten())
model.add(Dense(NC_2, activation=ACTIVATION))
model.add(Dense(PREDICTION, activation=ACTIVATION))
model.compile(loss= LOSS,
optimizer= OPTIMIZER_1,
metrics= METRICS)
return model
model_dmin_sic = model_MLP()
model_dmax_sic = model_MLP()
# Mostramos la estructura del modelo para la dmin (el mismo para los 2 tipos de demanda)
model_dmin_sic.summary()
# Entrenamos el modelo de dmin
history_dmin = model_dmin_sic.fit(x_train_dmin, y_train_dmin,
epochs=EPOCHS_1,
batch_size = BATCH_SIZE,
validation_data=(x_val_dmin,y_val_dmin))
# Entrenamos el modelo de dmax
history_dmax = model_dmax_sic.fit(x_train_dmax, y_train_dmax,
epochs=EPOCHS_1,
batch_size = BATCH_SIZE,
validation_data=(x_val_dmax,y_val_dmax))
hist_dmin = pd.DataFrame(history_dmin.history)
hist_dmin['epoch'] = history_dmin.epoch
# Mostramos las ultimas 5 filas del total de epoch de entrenamiento
hist_dmin.tail()
plot_history(history_dmin)
hist_dmax = pd.DataFrame(history_dmax.history)
hist_dmax['epoch'] = history_dmax.epoch
# Mostramos las ultimas 5 filas del total de epoch de entrenamiento
hist_dmax.tail()
plot_history(history_dmax)
modified_to_predict = normalize_and_supervised(pronostic_jul_dmin)
predict_jul_dmin = prediction(modified_to_predict, model_dmin_sic,2)
view_prediction = prediction_graph(predict_jul_dmin, pronostic_jul_dmin)
modified_to_predict = normalize_and_supervised(pronostic_august_dmin)
predict_august_dmin = prediction(modified_to_predict, model_dmin_sic,2)
view_prediction = prediction_graph(predict_august_dmin, pronostic_august_dmin)
modified_to_predict = normalize_and_supervised(pronostic_sept_dmin)
predict_sept_dmin = prediction(modified_to_predict, model_dmin_sic,2)
view_prediction = prediction_graph(predict_sept_dmin, pronostic_sept_dmin)
modified_to_predict = normalize_and_supervised(pronostic_oct_dmin)
predict_oct_dmin = prediction(modified_to_predict, model_dmin_sic,2)
view_prediction = prediction_graph(predict_oct_dmin, pronostic_oct_dmin)
modified_to_predict = normalize_and_supervised(pronostic_nov_dmin)
predict_nov_dmin = prediction(modified_to_predict, model_dmin_sic,2)
view_prediction = prediction_graph(predict_nov_dmin, pronostic_nov_dmin)
modified_to_predict = normalize_and_supervised(pronostic_dic_dmin)
predict_dic_dmin = prediction(modified_to_predict, model_dmin_sic,2)
view_prediction = prediction_graph(predict_dic_dmin, pronostic_dic_dmin)
modified_to_predict = normalize_and_supervised(pronostic_jul_dmax)
prediction_jul_dmax = prediction(modified_to_predict, model_dmax_sic,2)
view_prediction = prediction_graph(prediction_jul_dmax, pronostic_jul_dmax)
modified_to_predict = normalize_and_supervised(pronostic_august_dmax)
prediction_august_dmax = prediction(modified_to_predict, model_dmax_sic,2)
view_prediction = prediction_graph(prediction_august_dmax, pronostic_august_dmax)
modified_to_predict = normalize_and_supervised(pronostic_sept_dmax)
prediction_sept_dmax = prediction(modified_to_predict, model_dmax_sic,2)
view_prediction = prediction_graph(prediction_sept_dmax, pronostic_sept_dmax)
modified_to_predict = normalize_and_supervised(pronostic_oct_dmax)
prediction_oct_dmax = prediction(modified_to_predict, model_dmax_sic,2)
view_prediction = prediction_graph(prediction_oct_dmax, pronostic_oct_dmax)
modified_to_predict = normalize_and_supervised(pronostic_nov_dmax)
prediction_nov_dmax = prediction(modified_to_predict, model_dmax_sic,2)
view_prediction = prediction_graph(prediction_nov_dmax, pronostic_nov_dmax)
modified_to_predict = normalize_and_supervised(pronostic_dic_dmax)
prediction_dic_dmax = prediction(modified_to_predict, model_dmax_sic,2)
view_prediction = prediction_graph(prediction_dic_dmax, pronostic_dic_dmax)
def model_LSTM():
model = Sequential()
model.add(LSTM(NC_1, input_shape = (1, PAST_HISTORY), return_sequences=True))
#model.add(Dropout(rate=0.2))
model.add(LSTM(NC_2, return_sequences=True))
#model.add(Dropout(rate=0.2))
model.add(Flatten())
#model.add(Dense(128, activation=ACTIVATION))
model.add(Dense(NC_3, activation=ACTIVATION))
model.add(Dense(PREDICTION, activation=ACTIVATION))
model.compile(loss= LOSS,
optimizer= OPTIMIZER_1,
metrics= METRICS)
return model
model_dmin_sic = model_LSTM()
model_dmax_sic = model_LSTM()
# Mostramos la estructura del modelo para la dmin (el mismo para los 3 tipos de demanda)
model_dmin_sic.summary()
# Entrenamos el modelo de dmin
history_dmin = model_dmin_sic.fit(x_train_dmin, y_train_dmin,
epochs=EPOCHS_1,
batch_size = BATCH_SIZE,
validation_data=(x_val_dmin,y_val_dmin),
shuffle= False)
# Entrenamos el modelo de dmax
history_dmax = model_dmax_sic.fit(x_train_dmax, y_train_dmax,
epochs=EPOCHS_2,
batch_size = BATCH_SIZE,
validation_data=(x_val_dmax,y_val_dmax),
shuffle= False)
hist_dmin = pd.DataFrame(history_dmin.history)
hist_dmin['epoch'] = history_dmin.epoch
# Mostramos las ultimas 5 filas del total de epoch de entrenamiento
hist_dmin.tail()
plot_history(history_dmin)
hist_dmax = pd.DataFrame(history_dmax.history)
hist_dmax['epoch'] = history_dmax.epoch
# Mostramos las ultimas 5 filas del total de epoch de entrenamiento
hist_dmax.tail()
plot_history(history_dmax)
modified_to_predict = normalize_and_supervised(pronostic_jul_dmin)
predict_jul_dmin = prediction(modified_to_predict, model_dmin_sic,2)
view_prediction = prediction_graph(predict_jul_dmin, pronostic_jul_dmin)
modified_to_predict = normalize_and_supervised(pronostic_august_dmin)
predict_august_dmin = prediction(modified_to_predict, model_dmin_sic,2)
view_prediction = prediction_graph(predict_august_dmin, pronostic_august_dmin)
modified_to_predict = normalize_and_supervised(pronostic_sept_dmin)
predict_sept_dmin = prediction(modified_to_predict, model_dmin_sic,2)
view_prediction = prediction_graph(predict_sept_dmin, pronostic_sept_dmin)
modified_to_predict = normalize_and_supervised(pronostic_oct_dmin)
predict_oct_dmin = prediction(modified_to_predict, model_dmin_sic,2)
view_prediction = prediction_graph(predict_oct_dmin, pronostic_oct_dmin)
modified_to_predict = normalize_and_supervised(pronostic_nov_dmin)
predict_nov_dmin = prediction(modified_to_predict, model_dmin_sic,2)
view_prediction = prediction_graph(predict_nov_dmin, pronostic_nov_dmin)
modified_to_predict = normalize_and_supervised(pronostic_dic_dmin)
predict_dic_dmin = prediction(modified_to_predict, model_dmin_sic,2)
view_prediction = prediction_graph(predict_dic_dmin, pronostic_dic_dmin)
modified_to_predict = normalize_and_supervised(pronostic_jul_dmax)
prediction_jul_dmax = prediction(modified_to_predict, model_dmax_sic,2)
view_prediction = prediction_graph(prediction_jul_dmax, pronostic_jul_dmax)
modified_to_predict = normalize_and_supervised(pronostic_august_dmax)
prediction_august_dmax = prediction(modified_to_predict, model_dmax_sic,2)
view_prediction = prediction_graph(prediction_august_dmax, pronostic_august_dmax)
modified_to_predict = normalize_and_supervised(pronostic_sept_dmax)
prediction_sept_dmax = prediction(modified_to_predict, model_dmax_sic,2)
view_prediction = prediction_graph(prediction_sept_dmax, pronostic_sept_dmax)
modified_to_predict = normalize_and_supervised(pronostic_oct_dmax)
prediction_oct_dmax = prediction(modified_to_predict, model_dmax_sic,2)
view_prediction = prediction_graph(prediction_oct_dmax, pronostic_oct_dmax)
modified_to_predict = normalize_and_supervised(pronostic_nov_dmax)
prediction_nov_dmax = prediction(modified_to_predict, model_dmax_sic,2)
view_prediction = prediction_graph(prediction_nov_dmax, pronostic_nov_dmax)
modified_to_predict = normalize_and_supervised(pronostic_dic_dmax)
prediction_dic_dmax = prediction(modified_to_predict, model_dmax_sic,2)
view_prediction = prediction_graph(prediction_dic_dmax, pronostic_dic_dmax)
def model_GRU():
model = Sequential()
model.add(GRU(NC_1, input_shape = (1, PAST_HISTORY), return_sequences=True))
#model.add(Dropout(rate=0.2))
model.add(GRU(NC_2, return_sequences=True))
#model.add(Dropout(rate=0.2))
model.add(Flatten())
#model.add(Dense(128, activation=ACTIVATION))
model.add(Dense(NC_3, activation=ACTIVATION))
model.add(Dense(PREDICTION, activation=ACTIVATION))
model.compile(loss= LOSS,
optimizer= OPTIMIZER_1,
metrics= METRICS)
return model
model_dmin_sic = model_GRU()
model_dmax_sic = model_GRU()
# Mostramos la estructura del modelo para la dmin (el mismo para los 3 tipos de demanda)
model_dmin_sic.summary()
# Entrenamos el modelo de dmin
history_dmin = model_dmin_sic.fit(x_train_dmin, y_train_dmin,
epochs=EPOCHS_1,
batch_size = BATCH_SIZE,
validation_data=(x_val_dmin,y_val_dmin),
shuffle= False)
# Entrenamos el modelo de dmax
history_dmax = model_dmax_sic.fit(x_train_dmax, y_train_dmax,
epochs=EPOCHS_2,
batch_size = BATCH_SIZE,
validation_data=(x_val_dmax,y_val_dmax),
shuffle= False)
hist_dmin = pd.DataFrame(history_dmin.history)
hist_dmin['epoch'] = history_dmin.epoch
# Mostramos las ultimas 5 filas del total de epoch de entrenamiento
hist_dmin.tail()
plot_history(history_dmin)
hist_dmax = pd.DataFrame(history_dmax.history)
hist_dmax['epoch'] = history_dmax.epoch
# Mostramos las ultimas 5 filas del total de epoch de entrenamiento
hist_dmax.tail()
plot_history(history_dmax)
modified_to_predict = normalize_and_supervised(pronostic_jul_dmin)
#predict_jul_dmin = prediction(modified_to_predict, model_dmin)
predict_jul_dmin = prediction(modified_to_predict, model_dmin_sic,2)
view_prediction = prediction_graph(predict_jul_dmin, pronostic_jul_dmin)
modified_to_predict = normalize_and_supervised(pronostic_august_dmin)
predict_august_dmin = prediction(modified_to_predict, model_dmin_sic,2)
view_prediction = prediction_graph(predict_august_dmin, pronostic_august_dmin)
modified_to_predict = normalize_and_supervised(pronostic_sept_dmin)
predict_sept_dmin = prediction(modified_to_predict, model_dmin_sic,2)
view_prediction = prediction_graph(predict_sept_dmin, pronostic_sept_dmin)
modified_to_predict = normalize_and_supervised(pronostic_oct_dmin)
predict_oct_dmin = prediction(modified_to_predict, model_dmin_sic,2)
view_prediction = prediction_graph(predict_oct_dmin, pronostic_oct_dmin)
modified_to_predict = normalize_and_supervised(pronostic_nov_dmin)
predict_nov_dmin = prediction(modified_to_predict, model_dmin_sic,2)
view_prediction = prediction_graph(predict_nov_dmin, pronostic_nov_dmin)
modified_to_predict = normalize_and_supervised(pronostic_dic_dmin)
predict_dic_dmin = prediction(modified_to_predict, model_dmin_sic,2)
view_prediction = prediction_graph(predict_dic_dmin, pronostic_dic_dmin)
modified_to_predict = normalize_and_supervised(pronostic_jul_dmax)
prediction_jul_dmax = prediction(modified_to_predict, model_dmax_sic,1)
view_prediction = prediction_graph(prediction_jul_dmax, pronostic_jul_dmax)
modified_to_predict = normalize_and_supervised(pronostic_august_dmax)
prediction_august_dmax = prediction(modified_to_predict, model_dmax_sic,2)
view_prediction = prediction_graph(prediction_august_dmax, pronostic_august_dmax)
modified_to_predict = normalize_and_supervised(pronostic_sept_dmax)
prediction_sept_dmax = prediction(modified_to_predict, model_dmax_sic,2)
view_prediction = prediction_graph(prediction_sept_dmax, pronostic_sept_dmax)
modified_to_predict = normalize_and_supervised(pronostic_oct_dmax)
prediction_oct_dmax = prediction(modified_to_predict, model_dmax_sic,2)
view_prediction = prediction_graph(prediction_oct_dmax, pronostic_oct_dmax)
modified_to_predict = normalize_and_supervised(pronostic_nov_dmax)
prediction_nov_dmax = prediction(modified_to_predict, model_dmax_sic,2)
view_prediction = prediction_graph(prediction_nov_dmax, pronostic_nov_dmax)
modified_to_predict = normalize_and_supervised(pronostic_dic_dmax)
prediction_dic_dmax = prediction(modified_to_predict, model_dmax_sic,2)
view_prediction = prediction_graph(prediction_dic_dmax, pronostic_dic_dmax)
transform_data_dmin = normalize_and_supervised(sen_train_dmin)
transform_data_dmax = normalize_and_supervised(sen_train_dmax)
transform_data_dmin.shape
pronostic_feb_dmin = data_sen[['dmin']].loc['2020-09':'2021-02']
pronostic_mar_dmin = data_sen[['dmin']].loc['2020-10':'2021-03']
pronostic_abr_dmin = data_sen[['dmin']].loc['2020-11':'2021-04']
pronostic_may_dmin = data_sen[['dmin']].loc['2020-12':'2021-05']
pronostic_jun_dmin = data_sen[['dmin']].loc['2021-01':'2021-06']
pronostic_jul_dmin = data_sen[['dmin']].loc['2021-02':'2021-07']
pronostic_feb_dmax = data_sen[['dmax']].loc['2020-09':'2021-02']
pronostic_mar_dmax = data_sen[['dmax']].loc['2020-10':'2021-03']
pronostic_abr_dmax = data_sen[['dmax']].loc['2020-11':'2021-04']
pronostic_may_dmax = data_sen[['dmax']].loc['2020-12':'2021-05']
pronostic_jun_dmax = data_sen[['dmax']].loc['2021-01':'2021-06']
pronostic_jul_dmax = data_sen[['dmax']].loc['2021-02':'2021-07']
dividing_dmin = train_and_validation(transform_data_dmin)
x_train_dmin, y_train_dmin, x_val_dmin, y_val_dmin = dividing_dmin[0], dividing_dmin[1], dividing_dmin[2], dividing_dmin[3]
dividing_dmax = train_and_validation(transform_data_dmax)
x_train_dmax, y_train_dmax, x_val_dmax, y_val_dmax = dividing_dmax[0], dividing_dmax[1], dividing_dmax[2], dividing_dmax[3]
# Mostramos la dimensiones de los tensores de entrada.
print(x_train_dmin.shape, y_train_dmin.shape, x_val_dmin.shape, y_val_dmin.shape)
def model_MLP_sen():
model = Sequential()
model.add(Dense(NC_1, input_shape = (1, PAST_HISTORY), activation = ACTIVATION))
model.add(Flatten())
model.add(Dense(64, activation=ACTIVATION))
model.add(Dense(PREDICTION, activation=ACTIVATION))
model.compile(loss= LOSS,
optimizer= OPTIMIZER_1,
metrics= METRICS)
return model
model_dmin_sen = model_MLP_sen()
model_dmax_sen = model_MLP_sen()
# Mostramos la estructura del modelo para la dmin (el mismo para los 3 tipos de demanda)
model_dmin_sen.summary()
# Entrenamos el modelo de dmin
history_dmin = model_dmin_sen.fit(x_train_dmin, y_train_dmin,
epochs=EPOCHS_1,
batch_size = BATCH_SIZE,
validation_data=(x_val_dmin,y_val_dmin))
# Entrenamos el modelo de dmax
history_dmax = model_dmax_sen.fit(x_train_dmax, y_train_dmax,
epochs=EPOCHS_1,
batch_size = BATCH_SIZE,
validation_data=(x_val_dmax,y_val_dmax))
hist_dmin = pd.DataFrame(history_dmin.history)
hist_dmin['epoch'] = history_dmin.epoch
# Mostramos las ultimas 5 filas del total de epoch de entrenamiento
hist_dmin.tail()
plot_history(history_dmin)
hist_dmax = pd.DataFrame(history_dmax.history)
hist_dmax['epoch'] = history_dmax.epoch
# Mostramos las ultimas 5 filas del total de epoch de entrenamiento
hist_dmax.tail()
plot_history(history_dmax)
modified_to_predict = normalize_and_supervised(pronostic_feb_dmin)
predict_feb_dmin = prediction(modified_to_predict, model_dmin_sen)
view_prediction = prediction_graph(predict_feb_dmin, pronostic_feb_dmin)
modified_to_predict = normalize_and_supervised(pronostic_mar_dmin)
predict_mar_dmin = prediction(modified_to_predict, model_dmin_sen)
view_prediction = prediction_graph(predict_mar_dmin, pronostic_mar_dmin)
modified_to_predict = normalize_and_supervised(pronostic_abr_dmin)
predict_abr_dmin = prediction(modified_to_predict, model_dmin_sen)
view_prediction = prediction_graph(predict_abr_dmin, pronostic_abr_dmin)
modified_to_predict = normalize_and_supervised(pronostic_may_dmin)
predict_may_dmin = prediction(modified_to_predict, model_dmin_sen)
view_prediction = prediction_graph(predict_may_dmin, pronostic_may_dmin)
modified_to_predict = normalize_and_supervised(pronostic_jun_dmin)
predict_jun_dmin = prediction(modified_to_predict, model_dmin_sen)
view_prediction = prediction_graph(predict_jun_dmin, pronostic_jun_dmin)
modified_to_predict = normalize_and_supervised(pronostic_jul_dmin)
predict_jul_dmin = prediction(modified_to_predict, model_dmin_sen)
view_prediction = prediction_graph(predict_jul_dmin, pronostic_jul_dmin)
modified_to_predict = normalize_and_supervised(pronostic_feb_dmax)
prediction_feb_dmax = prediction(modified_to_predict, model_dmax_sen)
view_prediction = prediction_graph(prediction_feb_dmax, pronostic_feb_dmax)
modified_to_predict = normalize_and_supervised(pronostic_mar_dmax)
prediction_mar_dmax = prediction(modified_to_predict, model_dmax_sen)
view_prediction = prediction_graph(prediction_mar_dmax, pronostic_mar_dmax)
modified_to_predict = normalize_and_supervised(pronostic_abr_dmax)
prediction_abr_dmax = prediction(modified_to_predict, model_dmax_sen)
view_prediction = prediction_graph(prediction_abr_dmax, pronostic_abr_dmax)
modified_to_predict = normalize_and_supervised(pronostic_may_dmax)
prediction_may_dmax = prediction(modified_to_predict, model_dmax_sen)
view_prediction = prediction_graph(prediction_may_dmax, pronostic_may_dmax)
modified_to_predict = normalize_and_supervised(pronostic_jun_dmax)
prediction_jun_dmax = prediction(modified_to_predict, model_dmax_sen)
view_prediction = prediction_graph(prediction_jun_dmax, pronostic_jun_dmax)
modified_to_predict = normalize_and_supervised(pronostic_jul_dmax)
prediction_jul_dmax = prediction(modified_to_predict, model_dmax_sen)
view_prediction = prediction_graph(prediction_jul_dmax, pronostic_jul_dmax)
def model_LSTM_sen():
model = Sequential()
model.add(LSTM(NC_1, input_shape = (1, PAST_HISTORY), return_sequences=True))
#model.add(Dropout(rate=0.2))
#model.add(LSTM(NC_2, return_sequences=True))
#model.add(Dropout(rate=0.2))
model.add(Flatten())
#model.add(Dense(128, activation=ACTIVATION))
model.add(Dense(NC_3, activation=ACTIVATION))
model.add(Dense(PREDICTION, activation=ACTIVATION))
model.compile(loss= LOSS,
optimizer= OPTIMIZER_1,
metrics= METRICS)
return model
model_dmin_sen = model_LSTM_sen()
model_dmax_sen = model_LSTM_sen()
# Mostramos la estructura del modelo para la dmin (el mismo para los 3 tipos de demanda)
model_dmin_sen.summary()
# Entrenamos el modelo de dmin
history_dmin = model_dmin_sen.fit(x_train_dmin, y_train_dmin,
epochs=EPOCHS_1,
batch_size = BATCH_SIZE,
validation_data=(x_val_dmin,y_val_dmin),
shuffle= False)
# Entrenamos el modelo de dmax
history_dmax = model_dmax_sen.fit(x_train_dmax, y_train_dmax,
epochs=EPOCHS_1,
batch_size = BATCH_SIZE,
validation_data=(x_val_dmax,y_val_dmax),
shuffle= False)
hist_dmin = pd.DataFrame(history_dmin.history)
hist_dmin['epoch'] = history_dmin.epoch
# Mostramos las ultimas 5 filas del total de epoch de entrenamiento
hist_dmin.tail()
plot_history(history_dmin)
hist_dmax = pd.DataFrame(history_dmax.history)
hist_dmax['epoch'] = history_dmax.epoch
# Mostramos las ultimas 5 filas del total de epoch de entrenamiento
hist_dmax.tail()
plot_history(history_dmax)
modified_to_predict = normalize_and_supervised(pronostic_feb_dmin)
predict_feb_dmin = prediction(modified_to_predict, model_dmin_sen)
view_prediction = prediction_graph(predict_feb_dmin, pronostic_feb_dmin)
modified_to_predict = normalize_and_supervised(pronostic_mar_dmin)
predict_mar_dmin = prediction(modified_to_predict, model_dmin_sen)
view_prediction = prediction_graph(predict_mar_dmin, pronostic_mar_dmin)
modified_to_predict = normalize_and_supervised(pronostic_abr_dmin)
predict_abr_dmin = prediction(modified_to_predict, model_dmin_sen)
view_prediction = prediction_graph(predict_abr_dmin, pronostic_abr_dmin)
modified_to_predict = normalize_and_supervised(pronostic_may_dmin)
predict_may_dmin = prediction(modified_to_predict, model_dmin_sen)
view_prediction = prediction_graph(predict_may_dmin, pronostic_may_dmin)
modified_to_predict = normalize_and_supervised(pronostic_jun_dmin)
predict_jun_dmin = prediction(modified_to_predict, model_dmin_sen)
view_prediction = prediction_graph(predict_jun_dmin, pronostic_jun_dmin)
modified_to_predict = normalize_and_supervised(pronostic_jul_dmin)
predict_jul_dmin = prediction(modified_to_predict, model_dmin_sen)
view_prediction = prediction_graph(predict_jul_dmin, pronostic_jul_dmin)
modified_to_predict = normalize_and_supervised(pronostic_feb_dmax)
prediction_feb_dmax = prediction(modified_to_predict, model_dmax_sen)
view_prediction = prediction_graph(prediction_feb_dmax, pronostic_feb_dmax)
modified_to_predict = normalize_and_supervised(pronostic_mar_dmax)
prediction_mar_dmax = prediction(modified_to_predict, model_dmax_sen)
view_prediction = prediction_graph(prediction_mar_dmax, pronostic_mar_dmax)
modified_to_predict = normalize_and_supervised(pronostic_abr_dmax)
prediction_abr_dmax = prediction(modified_to_predict, model_dmax_sen)
view_prediction = prediction_graph(prediction_abr_dmax, pronostic_abr_dmax)
modified_to_predict = normalize_and_supervised(pronostic_may_dmax)
prediction_may_dmax = prediction(modified_to_predict, model_dmax_sen)
view_prediction = prediction_graph(prediction_may_dmax, pronostic_may_dmax)
modified_to_predict = normalize_and_supervised(pronostic_jun_dmax)
prediction_jun_dmax = prediction(modified_to_predict, model_dmax_sen)
view_prediction = prediction_graph(prediction_jun_dmax, pronostic_jun_dmax)
modified_to_predict = normalize_and_supervised(pronostic_jul_dmax)
prediction_jul_dmax = prediction(modified_to_predict, model_dmax_sen)
view_prediction = prediction_graph(prediction_jul_dmax, pronostic_jul_dmax)
def model_GRU():
model = Sequential()
model.add(GRU(NC_1, input_shape = (1, PAST_HISTORY), return_sequences=True))
#model.add(Dropout(rate=0.2))
#model.add(GRU(NC_2, return_sequences=True))
#model.add(Dropout(rate=0.2))
model.add(Flatten())
#model.add(Dense(128, activation=ACTIVATION))
model.add(Dense(NC_3, activation=ACTIVATION))
model.add(Dense(PREDICTION, activation=ACTIVATION))
model.compile(loss= LOSS,
optimizer= OPTIMIZER_1,
metrics= METRICS)
return model
model_dmin_sic = model_GRU()
#model_dmean = model_LSTM()
model_dmax_sic = model_GRU()
# Mostramos la estructura del modelo para la dmin (el mismo para los 3 tipos de demanda)
model_dmin_sic.summary()
# Entrenamos el modelo de dmin
history_dmin = model_dmin_sic.fit(x_train_dmin, y_train_dmin,
epochs=EPOCHS_1,
batch_size = BATCH_SIZE,
validation_data=(x_val_dmin,y_val_dmin),
shuffle= False)
# Entrenamos el modelo de dmean
#history_dmean = model_dmean.fit(x_train_dmean, y_train_dmean,
# epochs=EPOCHS,
# batch_size = BATCH_SIZE,
# validation_data=(x_val_dmean,y_val_dmean),
# shuffle= False)
# Entrenamos el modelo de dmax
history_dmax = model_dmax_sic.fit(x_train_dmax, y_train_dmax,
epochs=EPOCHS_1,
batch_size = BATCH_SIZE,
validation_data=(x_val_dmax,y_val_dmax),
shuffle= False)
hist_dmin = pd.DataFrame(history_dmin.history)
hist_dmin['epoch'] = history_dmin.epoch
# Mostramos las ultimas 5 filas del total de epoch de entrenamiento
hist_dmin.tail()
plot_history(history_dmin)
hist_dmax = pd.DataFrame(history_dmax.history)
hist_dmax['epoch'] = history_dmax.epoch
# Mostramos las ultimas 5 filas del total de epoch de entrenamiento
hist_dmax.tail()
plot_history(history_dmax)
modified_to_predict = normalize_and_supervised(pronostic_feb_dmin)
predict_feb_dmin = prediction(modified_to_predict, model_dmin_sen)
view_prediction = prediction_graph(predict_feb_dmin, pronostic_feb_dmin)
modified_to_predict = normalize_and_supervised(pronostic_mar_dmin)
predict_mar_dmin = prediction(modified_to_predict, model_dmin_sen)
view_prediction = prediction_graph(predict_mar_dmin, pronostic_mar_dmin)
modified_to_predict = normalize_and_supervised(pronostic_abr_dmin)
predict_abr_dmin = prediction(modified_to_predict, model_dmin_sen)
view_prediction = prediction_graph(predict_abr_dmin, pronostic_abr_dmin)
modified_to_predict = normalize_and_supervised(pronostic_may_dmin)
predict_may_dmin = prediction(modified_to_predict, model_dmin_sen)
view_prediction = prediction_graph(predict_may_dmin, pronostic_may_dmin)
modified_to_predict = normalize_and_supervised(pronostic_jun_dmin)
predict_jun_dmin = prediction(modified_to_predict, model_dmin_sen)
view_prediction = prediction_graph(predict_jun_dmin, pronostic_jun_dmin)
modified_to_predict = normalize_and_supervised(pronostic_jul_dmin)
predict_jul_dmin = prediction(modified_to_predict, model_dmin_sen)
view_prediction = prediction_graph(predict_jul_dmin, pronostic_jul_dmin)
modified_to_predict = normalize_and_supervised(pronostic_feb_dmax)
prediction_feb_dmax = prediction(modified_to_predict, model_dmax_sen)
view_prediction = prediction_graph(prediction_feb_dmax, pronostic_feb_dmax)
modified_to_predict = normalize_and_supervised(pronostic_mar_dmax)
prediction_mar_dmax = prediction(modified_to_predict, model_dmax_sen)
view_prediction = prediction_graph(prediction_mar_dmax, pronostic_mar_dmax)
modified_to_predict = normalize_and_supervised(pronostic_abr_dmax)
prediction_abr_dmax = prediction(modified_to_predict, model_dmax_sen)
view_prediction = prediction_graph(prediction_abr_dmax, pronostic_abr_dmax)
modified_to_predict = normalize_and_supervised(pronostic_may_dmax)
prediction_may_dmax = prediction(modified_to_predict, model_dmax_sen)
view_prediction = prediction_graph(prediction_may_dmax, pronostic_may_dmax)
modified_to_predict = normalize_and_supervised(pronostic_jun_dmax)
prediction_jun_dmax = prediction(modified_to_predict, model_dmax_sen)
view_prediction = prediction_graph(prediction_jun_dmax, pronostic_jun_dmax)
modified_to_predict = normalize_and_supervised(pronostic_jul_dmax)
prediction_jul_dmax = prediction(modified_to_predict, model_dmax_sen)
view_prediction = prediction_graph(prediction_jul_dmax, pronostic_jul_dmax)