-
Notifications
You must be signed in to change notification settings - Fork 0
/
mld_test.txt
221 lines (175 loc) · 8.28 KB
/
mld_test.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
import tensorflow as tf
# Carregar os dados
input_train = pd.read_csv('C:/project_topicos_especiais/prediction_calories/prediction_calories/dataset/train/input_train.csv')
output_train = pd.read_csv('C:/project_topicos_especiais/prediction_calories/prediction_calories/dataset/train/output_train.csv')
input_test = pd.read_csv('C:/project_topicos_especiais/prediction_calories/prediction_calories/dataset/test/input_test.csv')
output_test = pd.read_csv('C:/project_topicos_especiais/prediction_calories/prediction_calories/dataset/test/output_test.csv')
# Normalizar os dados
scaler_input = StandardScaler()
i_train = scaler_input.fit_transform(input_train)
i_test = scaler_input.transform(input_test)
scaler_output = StandardScaler()
o_train = scaler_output.fit_transform(output_train.values.reshape(-1, 1))
o_test = scaler_output.transform(output_test.values.reshape(-1, 1))
# Definir o modelo
model = tf.keras.models.Sequential([
tf.keras.layers.Dense(128, activation='relu', input_shape=(i_train.shape[1],)),
tf.keras.layers.Dropout(0.3),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dropout(0.3),
tf.keras.layers.Dense(32, activation='relu'),
tf.keras.layers.Dropout(0.3),
tf.keras.layers.Dense(1, activation='linear') # Saída única para regressão
])
# Configurar early stopping
early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=10, mode='min', restore_best_weights=True)
# Compilar o modelo
model.compile(optimizer='adam', loss='mse', metrics=['mae'])
# Resumir o modelo
model.summary()
# Treinar o modelo
history = model.fit(i_train, o_train, epochs=100, validation_split=0.2, callbacks=[early_stopping])
# Avaliar o modelo no conjunto de teste
test_loss, test_mae = model.evaluate(i_test, o_test)
print(f'Test Loss: {test_loss}, Test MAE: {test_mae}')
# Fazer previsões no conjunto de teste
predicoes = model.predict(i_test)
# Inverter a normalização das previsões
predicoes_inverted = scaler_output.inverse_transform(predicoes)
output_test_inverted = scaler_output.inverse_transform(o_test)
# Exibir previsões
print(predicoes_inverted[:10])
print(output_test_inverted[:10])
# Plotar a perda durante o treinamento
plt.plot(history.history['loss'], label='train')
plt.plot(history.history['val_loss'], label='validation')
plt.legend()
plt.yscale('log')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.title('Training and Validation Loss')
plt.show()
# Comparar valores reais e previstos
plt.scatter(output_test_inverted, predicoes_inverted, alpha=0.5)
plt.plot([output_test_inverted.min(), output_test_inverted.max()], [output_test_inverted.min(), output_test_inverted.max()], 'r--')
plt.xlabel('True Values')
plt.ylabel('Predictions')
plt.title('True vs Predicted Values')
plt.show()
=========================================================================================================================================
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
import tensorflow as tf
# Carregar os dados
input_train = pd.read_csv('C:/project_topicos_especiais/prediction_calories/prediction_calories/dataset/train/input_train.csv')
output_train = pd.read_csv('C:/project_topicos_especiais/prediction_calories/prediction_calories/dataset/train/output_train.csv')
input_test = pd.read_csv('C:/project_topicos_especiais/prediction_calories/prediction_calories/dataset/test/input_test.csv')
output_test = pd.read_csv('C:/project_topicos_especiais/prediction_calories/prediction_calories/dataset/test/output_test.csv')
# Normalizar os dados
scaler_input = StandardScaler()
i_train = scaler_input.fit_transform(input_train)
i_test = scaler_input.transform(input_test)
scaler_output = StandardScaler()
o_train = scaler_output.fit_transform(output_train.values.reshape(-1, 1))
o_test = scaler_output.transform(output_test.values.reshape(-1, 1))
# Definir o modelo
model = tf.keras.models.Sequential([
tf.keras.layers.Dense(128, activation='relu', input_shape=(i_train.shape[1],)),
tf.keras.layers.Dropout(0.3),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dropout(0.3),
tf.keras.layers.Dense(32, activation='relu'),
tf.keras.layers.Dropout(0.3),
tf.keras.layers.Dense(1, activation='linear') # Saída única para regressão
])
# Configurar early stopping
early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=10, mode='min', restore_best_weights=True)
# Compilar o modelo
model.compile(optimizer='adam', loss='mse', metrics=['mae'])
# Resumir o modelo
model.summary()
# Treinar o modelo
history = model.fit(i_train, o_train, epochs=100, validation_split=0.2, callbacks=[early_stopping])
# Avaliar o modelo no conjunto de teste
test_loss, test_mae = model.evaluate(i_test, o_test)
print(f'Test Loss: {test_loss}, Test MAE: {test_mae}')
# Fazer previsões no conjunto de teste
predicoes = model.predict(i_test)
# Inverter a normalização das previsões
predicoes_inverted = scaler_output.inverse_transform(predicoes)
output_test_inverted = scaler_output.inverse_transform(o_test)
# Exibir previsões
print(predicoes_inverted[:10])
print(output_test_inverted[:10])
# Plotar a perda durante o treinamento
plt.plot(history.history['loss'], label='train')
plt.plot(history.history['val_loss'], label='validation')
plt.legend()
plt.yscale('log')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.title('Training and Validation Loss')
plt.show()
# Comparar valores reais e previstos
plt.scatter(output_test_inverted, predicoes_inverted, alpha=0.5)
plt.plot([output_test_inverted.min(), output_test_inverted.max()], [output_test_inverted.min(), output_test_inverted.max()], 'r--')
plt.xlabel('True Values')
plt.ylabel('Predictions')
plt.title('True vs Predicted Values')
plt.show()
================================================================================================================================================
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
import tensorflow as tf
import shap
# Carregar os dados
input_train = pd.read_csv('C:/project_topicos_especiais/prediction_calories/prediction_calories/dataset/train/input_train.csv')
output_train = pd.read_csv('C:/project_topicos_especiais/prediction_calories/prediction_calories/dataset/train/output_train.csv')
input_test = pd.read_csv('C:/project_topicos_especiais/prediction_calories/prediction_calories/dataset/test/input_test.csv')
output_test = pd.read_csv('C:/project_topicos_especiais/prediction_calories/prediction_calories/dataset/test/output_test.csv')
# Verificar a forma dos dados
print("input_train shape:", input_train.shape)
print("output_train shape:", output_train.shape)
print("input_test shape:", input_test.shape)
print("output_test shape:", output_test.shape)
# Definir o modelo
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Dense(64, activation='relu', input_shape=(input_train.shape[1],)))
model.add(tf.keras.layers.Dropout(0.5))
model.add(tf.keras.layers.Dense(64, activation='relu'))
model.add(tf.keras.layers.Dropout(0.5))
model.add(tf.keras.layers.Dense(1, activation='linear')) # Ajustar unidades conforme a saída
# Configurar early stopping
early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=5, mode='min', restore_best_weights=True)
# Compilar o modelo
model.compile(optimizer='adam', loss='mse')
# Resumir o modelo
model.summary()
# Treinar o modelo
history = model.fit(input_train, output_train, epochs=100, validation_split=0.2, callbacks=[early_stopping])
# Fazer previsões
predicoes = model.predict(input_test)
# Se necessário, aplicar inversão de normalização
scaler_output = StandardScaler()
output_test_scaled = scaler_output.fit_transform(output_test.values.reshape(-1, 1))
predicoes_inverted = scaler_output.inverse_transform(predicoes)
# Exibir previsões
print(predicoes_inverted)
# Plotar o histórico de treinamento
plt.plot(history.history['loss'], label='train')
plt.plot(history.history['val_loss'], label='validation')
plt.legend()
plt.yscale('log')
plt.show()
# SHAP para explicabilidade
#explainer = shap.KernelExplainer(model.predict, input_test)
#shap_values = explainer.shap_values(input_test)
#shap.summary_plot(shap_values, input_test)