-
Notifications
You must be signed in to change notification settings - Fork 2
/
Report.py
283 lines (224 loc) · 9.49 KB
/
Report.py
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
from reportlab.lib import colors
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
from reportlab.lib.units import cm
from reportlab.lib import utils
from reportlab.platypus import Table, TableStyle, Image
from Methods import ExploratoryDataAnalysis as EDA
from Methods import ModelEvaluation
from Methods import util
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime
def InsertSection(c, dy, texto, cursor):
c.saveState()
c.translate(0, cursor+dy)
# Draw Rectangle
c.setFillColorRGB(0.74,0.84,0.93)
c.rect(0, 0, WIDTH - 2*MARGIN_X, 1*cm, fill=1, stroke=0)
# Write Title
x = (WIDTH - 2*MARGIN_X)/2
c.setFont("Helvetica", 14)
c.setFillColorRGB(0,0,0)
c.drawCentredString(x, 0.3*cm, texto)
c.restoreState()
cursor -= dy + 1*cm
cursor = SkipLine(cursor,0)
return cursor
def InsertField(table, c, cursor):
lins, cols = np.array(table).shape
style = TableStyle([('LINEBELOW', (0,0), (-1,-1), 1, colors.black),
('FACE', (0,0), (-1,-1), 'Helvetica'),
('SIZE', (0,0), (-1,-1), 12),
('VALIGN', (0,0), (-1,-1), 'MIDDLE'),
('TEXTCOLOR',(1,0),(1,-1),colors.Color(0.4,0.4,0.4)),
('ALIGN', (0,0), (-1,-1), 'LEFT')])
for l in range(lins):
if(l%2 == 0):
style.add('BACKGROUND', (0,l), (-1,l), colors.Color(0.9,0.9,0.9))
t = Table(table, style=style, rowHeights = LIN_HEIGHT)
sizex, sizey = t.wrap(WIDTH, HEIGHT)
cursor -= sizey
t.drawOn(c, 0, cursor)
cursor = SkipLine(cursor, n=2)
return cursor
def InsertImage(path, c, width, cursor):
# Adjust aspect ratio
img = utils.ImageReader(path)
iw, ih = img.getSize()
aspect = ih / float(iw)
img = Image(path, width=width, height=(width * aspect))
img.drawOn(c, 0, cursor)
cursor -= img.imageHeight
return cursor
def SkipLine(cursor, n=1):
cursor -= n*LIN_HEIGHT
return cursor
def Generate(model, modelName, codes, X_train, Y_train, X_test, Y_test, path='Reports/'):
# Generate needed variables
X = pd.concat([X_train, X_test])
Y = pd.concat([Y_train, Y_test])
predictions_test = model.predict(X_test)
predictions_train = model.predict(X_train)
data = datetime.now()
nomeArquivo = 'relatorio'+ data.strftime('_%d_%m_%Y-%H_%M_%S') + '.pdf'
titulo = 'Relatório do Modelo'
dataString = data.strftime('%d/%m/%Y %H:%M:%S')
colunas = list(X_train.columns)
ModelEvaluation.PlotFeatureImportanceXGBoost(model, save=True, path='images',
filename='feature_importance')
uniqueValues = EDA.UniqueValuesOnEachColumn(X)
ClassBalance = EDA.CalculateClassBalance(Y.to_frame(), get=True)
EDA.PlotCodeFrequency(codes, Y, save = True, path ='images',
filename = 'code_frequency')
metrics_test = ModelEvaluation.EvaluateClassification(Y_test, predictions_test,
'classifier_scores_v3',
save=True,
path='images',
imgname='confusion_matrix_test')
ModelEvaluation.PlotAccuracyOfEachEventCode(codes[len(Y_train):], Y_test,
predictions_test, save = True,
path='images',
filename = 'accuracy_by_code_test')
metrics_train = ModelEvaluation.EvaluateClassification(Y_train, predictions_train,
'classifier_scores_v3',
save=True,
path='images',
imgname='confusion_matrix_train')
ModelEvaluation.PlotAccuracyOfEachEventCode(codes[:len(Y_train)], Y_train,
predictions_train, save = True,
path='images',
filename = 'accuracy_by_code_train')
# Create document
# if directory doesnt exist, create it
util.CheckAndCreatePath(path)
c = canvas.Canvas(path + nomeArquivo, pagesize=A4)
global WIDTH
global HEIGHT
global MARGIN_Y
global MARGIN_X
global LIN_HEIGHT
WIDTH, HEIGHT = A4
MARGIN_Y = 2.54*cm
MARGIN_X = 1.5*cm
LIN_HEIGHT = 0.8*cm
c.translate(MARGIN_X, 0)
cursor = HEIGHT - MARGIN_Y
##########
# Page 1 #
##########
# Title
c.saveState()
c.translate(0, cursor)
c.setFont("Helvetica", 20)
c.setFillColorRGB(0,0,0)
x = (WIDTH - 2*MARGIN_X)/2
c.drawCentredString(x, 0, titulo)
cursor -= 1.3*cm
c.restoreState()
c.saveState()
c.translate(0, cursor)
c.setFont("Helvetica", 20)
c.drawCentredString(x, 0, dataString)
cursor -= 1.3*cm
c.restoreState()
cursor = SkipLine(cursor,1)
# Sobre o Modelo
cursor = InsertSection(c, 0, 'Modelo', cursor)
table = [['Modelo:', modelName],
['Número de Atributos:', len(colunas)]]
cursor = InsertField(table, c, cursor)
c.saveState()
c.translate(7*cm, 12.6*cm)
_ = InsertImage('images/feature_importance.png', c, 11*cm, 0)
c.restoreState()
cursor = SkipLine(cursor, n=3)
c.showPage()
##########
# Page 2 #
##########
# About the Dataset
c.translate(MARGIN_X, 0)
cursor = HEIGHT - MARGIN_Y
cursor = InsertSection(c, 0, 'Dataset', cursor)
# Unique Values on each column feature
table2 = list()
for col in uniqueValues.keys():
table2.append([col, uniqueValues[col]])
cursor = InsertField(table2, c, cursor)
# Class Balance Plot
NumToClass = lambda n: 'DP' if (n == 1) else 'DI'
percentage = lambda n, total: (n * 100.0) / total
total = sum(ClassBalance.values())
valueInPercentage = [percentage(x,total) for x in ClassBalance.values()]
labels = list(map(NumToClass, ClassBalance.keys()))
colors = ['#5B9BD5', '#BDD7EE']
plt.pie(valueInPercentage, labels=labels, colors=colors, startangle=120,frame=False, autopct='%.1f %%')
centre_circle = plt.Circle((0,0),0.5,color='black', fc='white',linewidth=0)
fig = plt.gcf()
fig.gca().add_artist(centre_circle)
plt.title('Balanceamento', fontsize=14)
plt.axis('equal')
plt.tight_layout()
plt.show()
fig.savefig('images/class_balance_plot.png', bbox_inches='tight', transparent=True)
# Show Class Balance Plot
c.saveState()
c.translate(8.5*cm, 18.3*cm)
_ = InsertImage('images/class_balance_plot.png', c, 12*cm, 0)
c.restoreState()
# Codes distribution on the dataset
c.saveState()
c.translate(0*cm, MARGIN_Y)
_ = InsertImage('images/code_frequency.png', c, 17.5*cm, 0)
c.restoreState()
c.showPage()
##########
# Page 3 #
##########
# Metrics - Test
c.translate(MARGIN_X, 0)
cursor = HEIGHT - MARGIN_Y
sectionTitle = 'Métricas - Teste (%.2f %% - %d)' %(percentage(len(X_test),len(X)), len(X_test))
cursor = InsertSection(c, 0, sectionTitle, cursor)
# tabela com as métricas
table3 =[['Acurácia:', '%.2f %%' % (metrics_test['accuracy'] * 100)],
['MCC:', '%.5f' % (metrics_test['mcc'])],
['Macro-F1:', '%.5f' % (metrics_test['macrof1'])],
['Micro-F1:', '%.5f' % (metrics_test['microf1'])],
['AUC ROC:', '%.5f' % (metrics_test['rocauc'])]]
cursor = InsertField(table3, c, cursor)
c.saveState()
c.translate(6*cm, 16*cm)
_ = InsertImage('images/confusion_matrix_test.png', c, 12*cm, 0)
c.restoreState()
c.saveState()
c.translate(0*cm, MARGIN_Y)
_ = InsertImage('images/accuracy_by_code_test.png', c, 17.5*cm, 0)
c.restoreState()
c.showPage()
##########
# Page 4 #
##########
# Metrics - Train
c.translate(MARGIN_X, 0)
cursor = HEIGHT - MARGIN_Y
sectionTitle = 'Métricas - Treino (%.2f %% - %d)' %(percentage(len(X_train),len(X)), len(X_train))
cursor = InsertSection(c, 0, sectionTitle, cursor)
table4 =[['Acurácia:', '%.2f %%' % (metrics_train['accuracy'] * 100)],
['MCC:', '%.5f' % (metrics_train['mcc'])],
['Macro-F1:', '%.5f' % (metrics_train['macrof1'])],
['Micro-F1:', '%.5f' % (metrics_train['microf1'])],
['AUC ROC:', '%.5f' % (metrics_train['rocauc'])]]
cursor = InsertField(table4, c, cursor)
c.saveState()
c.translate(6*cm, 16*cm)
_ = InsertImage('images/confusion_matrix_train.png', c, 12*cm, 0)
c.restoreState()
c.saveState()
c.translate(0*cm, MARGIN_Y)
_ = InsertImage('images/accuracy_by_code_train.png', c, 17.5*cm, 0)
c.restoreState()
c.showPage()
c.save()