Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -59,11 +59,37 @@ class LSTM(nn.Module):
|
|
59 |
out = self.fc(out[:, -1, :])
|
60 |
return out
|
61 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
st.title('Predicción de Series de Tiempo')
|
63 |
st.sidebar.title('Parámetros del Modelo')
|
64 |
|
65 |
model_type = st.sidebar.selectbox('Selecciona el modelo', ('LSTM', 'Otro Modelo'))
|
66 |
-
num_epochs = st.sidebar.slider('Número de épocas', 100,
|
67 |
# learning_rate = st.sidebar.number_input('Tasa de aprendizaje', 0.001, 0.1, 0.01, 0.001)
|
68 |
|
69 |
if model_type == 'LSTM':
|
@@ -75,7 +101,7 @@ if model_type == 'LSTM':
|
|
75 |
model = LSTM(input_size, hidden_size, num_layers, output_size)
|
76 |
|
77 |
criterion = nn.MSELoss()
|
78 |
-
|
79 |
|
80 |
if st.sidebar.button('Entrenar y Predecir'):
|
81 |
for epoch in range(num_epochs):
|
@@ -129,3 +155,54 @@ if model_type == 'LSTM':
|
|
129 |
# ax.legend()
|
130 |
# ax.grid(True)
|
131 |
# st.pyplot(fig)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
59 |
out = self.fc(out[:, -1, :])
|
60 |
return out
|
61 |
|
62 |
+
#CLASE GRU
|
63 |
+
class GRU(nn.Module):
|
64 |
+
def __init__(self, input_size, hidden_size, num_layers, output_size):
|
65 |
+
super(GRU, self).__init__()
|
66 |
+
self.hidden_size = hidden_size
|
67 |
+
self.num_layers = num_layers
|
68 |
+
self.gru = nn.GRU(input_size, hidden_size, num_layers, batch_first=True)
|
69 |
+
self.fc = nn.Linear(hidden_size, output_size)
|
70 |
+
self.relu = nn.ReLU()
|
71 |
+
self.dropout = nn.Dropout(0.3) # Dropout para regularización
|
72 |
+
|
73 |
+
# Inicialización de los pesos de la capa lineal
|
74 |
+
nn.init.xavier_normal_(self.fc.weight)
|
75 |
+
|
76 |
+
def forward(self, x):
|
77 |
+
# Inicialización de los estados ocultos
|
78 |
+
h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(x.device)
|
79 |
+
|
80 |
+
# Propagación a través de la capa GRU
|
81 |
+
out, _ = self.gru(x, h0)
|
82 |
+
|
83 |
+
# Última capa GRU
|
84 |
+
out = self.fc(out[:, -1, :])
|
85 |
+
|
86 |
+
return out
|
87 |
+
|
88 |
st.title('Predicción de Series de Tiempo')
|
89 |
st.sidebar.title('Parámetros del Modelo')
|
90 |
|
91 |
model_type = st.sidebar.selectbox('Selecciona el modelo', ('LSTM', 'Otro Modelo'))
|
92 |
+
num_epochs = st.sidebar.slider('Número de épocas', 100, 200)
|
93 |
# learning_rate = st.sidebar.number_input('Tasa de aprendizaje', 0.001, 0.1, 0.01, 0.001)
|
94 |
|
95 |
if model_type == 'LSTM':
|
|
|
101 |
model = LSTM(input_size, hidden_size, num_layers, output_size)
|
102 |
|
103 |
criterion = nn.MSELoss()
|
104 |
+
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
|
105 |
|
106 |
if st.sidebar.button('Entrenar y Predecir'):
|
107 |
for epoch in range(num_epochs):
|
|
|
155 |
# ax.legend()
|
156 |
# ax.grid(True)
|
157 |
# st.pyplot(fig)
|
158 |
+
else :
|
159 |
+
input_size = 1
|
160 |
+
hidden_size = 50
|
161 |
+
num_layers = 2
|
162 |
+
output_size = 1
|
163 |
+
|
164 |
+
model = GRU(input_size, hidden_size, num_layers, output_size)
|
165 |
+
|
166 |
+
criterion = nn.MSELoss()
|
167 |
+
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
|
168 |
+
|
169 |
+
if st.sidebar.button('Entrenar y Predecir'):
|
170 |
+
for epoch in range(num_epochs):
|
171 |
+
model.train()
|
172 |
+
outputs = model(trainX)
|
173 |
+
optimizer.zero_grad()
|
174 |
+
loss = criterion(outputs, trainY)
|
175 |
+
loss.backward()
|
176 |
+
optimizer.step()
|
177 |
+
if (epoch+1) % 100 == 0:
|
178 |
+
st.write(f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}')
|
179 |
+
|
180 |
+
model.eval()
|
181 |
+
train_predict = model(trainX)
|
182 |
+
test_predict = model(testX)
|
183 |
+
|
184 |
+
train_predict = scaler.inverse_transform(train_predict.detach().numpy().reshape(-1, 1))
|
185 |
+
trainY_plot = scaler.inverse_transform(trainY.numpy().reshape(-1, 1))
|
186 |
+
test_predict = scaler.inverse_transform(test_predict.detach().numpy().reshape(-1, 1))
|
187 |
+
testY_plot = scaler.inverse_transform(testY.numpy().reshape(-1, 1))
|
188 |
+
|
189 |
+
train_data = pd.DataFrame({
|
190 |
+
'Fecha': filtered_data1['FECHA'].values[seq_length:seq_length+len(trainY)],
|
191 |
+
'Datos de entrenamiento': trainY_plot.ravel(),
|
192 |
+
'Predicciones de entrenamiento': train_predict.ravel()
|
193 |
+
})
|
194 |
+
|
195 |
+
test_data = pd.DataFrame({
|
196 |
+
'Fecha': filtered_data2['FECHA'].values[seq_length:seq_length+len(testY)],
|
197 |
+
'Datos de prueba': testY_plot.ravel(),
|
198 |
+
'Predicciones de prueba': test_predict.ravel()
|
199 |
+
})
|
200 |
+
|
201 |
+
# Concatenar los datos para tener una sola tabla
|
202 |
+
combined_data = pd.concat([train_data, test_data])
|
203 |
+
|
204 |
+
# Ajustar el índice
|
205 |
+
combined_data.set_index('Fecha', inplace=True)
|
206 |
+
|
207 |
+
# Mostrar la gráfica en Streamlit
|
208 |
+
st.line_chart(combined_data)
|