This repository has been archived by the owner on Jul 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathensemblemodels.py
284 lines (214 loc) · 10 KB
/
ensemblemodels.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
import pandas as pd
import numpy as np
import streamlit as st
import pickle
import time
from sklearn.preprocessing import MinMaxScaler,StandardScaler
mms = MinMaxScaler() # Normalization
ss = StandardScaler() # Standardization
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
import base64
from fpdf import FPDF
from pathlib import Path
from jinja2 import Template
class EnsembleModels():
def __init__(self):
self.__name = st.text_input('Enter your name')
self.__sex = st.selectbox('Enter your sex', options=('M', 'F'))
self.__age = st.number_input('Enter your age', min_value=18, max_value=110)
self.__pain_type = st.selectbox('Enter your chest pain type', options=('ASY','NAP','ATA','TA'))
self.__cholesterol = st.number_input('Enter your cholesterol', max_value=400)
self.__FastingBS = st.selectbox('Enter your fasting blood sugar (0 -> Normal; 1-> High)', options=(0,1))
self.__maxhr = st.number_input('Enter your maximum heart rate', max_value=250)
self.__exerangina = st.selectbox('Do you have exercise angina (N -> No; Y -> Yes)', options=('N', 'Y'))
self.__oldpeak = st.number_input('Enter old peak range')
self.__st_slope = st.selectbox('Enter ST Slope codition', options=('Up','Down','Flat'))
def __generate_report(self):
# report = '''
# This is a auto-generated report
# Name : {{self.__name}}
# f"# Report\n\n## Name: {self.name}\n\n## Date: {self.date}"
# ---
# Generated by MyReportGenerator v1.0'''
name = self.__name
if self.__sex == 0:
sex = 'Male'
else:
sex = 'Female'
age = self.__age
if self.__pain_type == 2:
pain_type = 'Non-Anginal Chest Pain'
elif self.__pain_type == 1:
pain_type = 'Atypical Angina'
elif self.__pain_type == 0:
pain_type = 'Asymptomatic'
elif self.__pain_type == 3:
pain_type = 'Typical Angina'
if self.__exerangina == 0:
exerangina = 'No'
else:
exerangina = 'Yes'
if self.__st_slope == 2:
st_slope = "Up"
elif self.__st_slope == 1:
st_slope = 'Flat'
elif self.__st_slope == 0:
st_slope = 'Down'
cholesterol = self.__cholesterol
max_hr = self.__maxhr
template_str = """
This is a auto-generated report
Name: {{ name }}
Age : {{ age }}
Sex : {{ sex }}
Pain Type : {{ pain_type }}
Exercise Angina : {{ exerangina }}
ST Slope : {{ st_slope }}
Cholesterol : {{ cholesterol }}
Maximum Heart Rate : {{ max_hr }}
"""
template = Template(template_str)
rendered_content = template.render(name=name, age=age, sex=sex, pain_type=pain_type, exerangina=exerangina, st_slope=st_slope, cholesterol=cholesterol, max_hr=max_hr)
# b64_report = base64.b64encode(report.encode()).decode()
b64_report = base64.b64encode(rendered_content.encode()).decode()
href = f'<a href="data:text/plain;base64,{b64_report}" download="AutoGen_Report.txt">Download Report</a>'
# href = f'<a href="data:text/plain;base64,{b64_report}" download="AutoGen_Report.txt">Download Report</a>'
# Display the link
st.markdown(href, unsafe_allow_html=True)
time.sleep(15)
filename = "AutoGen_Report.txt"
downloads_folder = Path.home() / "Downloads"
file_path = downloads_folder / filename
if file_path.exists():
text_file_path = file_path
output_pdf_path = downloads_folder/"AutoGen_Report.pdf"
self.convert_text_to_pdf(text_file_path, output_pdf_path)
else:
st.warning('It seems like the report has not been downloaded. If you would like to access the report, please perform the prediction again.')
# text_file_path = 'C:/Users/Aditya/Downloads/output.txt'
# output_pdf_path = 'C:/Users/Aditya/Downloads/output.pdf'
# self.convert_text_to_pdf(text_file_path, output_pdf_path)
def __preprocess(self):
if self.__sex == 'M':
self.__sex = 0
else:
self.__sex = 1
if self.__pain_type == 'NAP':
self.__pain_type = 2
elif self.__pain_type == 'ATA':
self.__pain_type = 1
elif self.__pain_type == 'ASY':
self.__pain_type = 0
elif self.__pain_type == 'TA':
self.__pain_type = 3
if self.__exerangina == 'N':
self.__exerangina = 0
else:
self.__exerangina = 1
if self.__st_slope == 'Up':
self.__st_slope = 2
elif self.__st_slope == 'Flat':
self.__st_slope = 1
elif self.__st_slope == 'Down':
self.__st_slope = 0
data = {
'age': self.__age,
'sex': self.__sex,
'pain_type': self.__pain_type,
'cholesterol': self.__cholesterol,
'FastingBS': self.__FastingBS,
'maxhr': self.__maxhr,
'exerangina': self.__exerangina,
'oldpeak': self.__oldpeak,
'st_slope': self.__st_slope
}
df1 = pd.DataFrame(data, index=[0])
return df1
def convert_text_to_pdf(self,text_file_path, output_pdf_path):
# Read the contents of the text file
with open(text_file_path, 'r') as file:
text = file.read()
pdf = FPDF()
pdf.add_page()
pdf.set_font('Arial', size=12)
pdf.multi_cell(0, 10, text)
pdf.output(output_pdf_path)
st.success('Both PDF and text version of the report downloaded!')
def predict(self):
btn = st.button('Predict',key='predict')
st.markdown('<hr>', unsafe_allow_html=True)
if "button1" not in st.session_state:
st.session_state["button1"] = False
if btn:
with st.spinner('Performing heart disease prediction... Please wait.'):
time.sleep(5)
st.success('Prediction complete!')
model_dt = pickle.load(open('Predictions/Models/dt_model.pkl', 'rb'))
model_knn = pickle.load(open('Predictions/Models/knn_model.pkl', 'rb'))
model_lr = pickle.load(open('Predictions/Models/lr_model.pkl', 'rb'))
model_rf = pickle.load(open('Predictions/Models/rf_model.pkl', 'rb'))
model_svm = pickle.load(open('Predictions/Models/svc_model.pkl', 'rb'))
df = self.__preprocess()
query = df.values
models = {
"Decision Tree": model_dt,
"K-Nearest Neighbors": model_knn,
"Logistic Regression": model_lr,
"Random Forest": model_rf,
"Support Vector Machine": model_svm
}
predictions = []
for model_name, model in models.items():
prediction = model.predict(query)
predictions.append(prediction)
result = "you DO NOT have heart disease" if prediction == 0 else "you HAVE a chance of heart disease"
# st.write(f"According to {model_name}: {result}\n")
flat_predictions = np.ravel(predictions)
majority_vote = np.bincount(flat_predictions).argmax()
final_result = "you DO NOT have heart disease" if majority_vote == 0 else "you HAVE a chance of heart disease"
# Display the results in a table
styled_table = '''
<style>
.styled-table {
border-collapse: collapse;
width: 100%;
margin-bottom: 20px;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
}
.styled-table th, .styled-table td {
border: 1px solid #dddddd;
padding: 8px;
color: black; /* Set the font color to black */
}
.styled-table th {
background-color: #f2f2f2;
}
.styled-table tr:nth-child(even) {
background-color: #f9f9f9;
}
.styled-table tr:nth-child(odd) {
background-color: #ffffff;
}
</style>
'''
styled_table += '<table class="styled-table"><tr><th>Model</th><th>Prediction</th></tr>'
for model_name, prediction in zip(models.keys(), predictions):
result = "you DO NOT have heart disease" if prediction == 0 else "you HAVE a chance of heart disease"
styled_table += f'<tr><td>{model_name}</td><td>{result}</td></tr>'
styled_table += '</table>'
color = "green" if majority_vote == 0 else "red"
# Combine the styled table and final result
styled_output = styled_table + f"<h4>Final Result (Majority Vote): <span style='color:{color}'>{final_result}</span></h4>"
st.markdown(styled_output, unsafe_allow_html=True)
st.markdown('<hr>', unsafe_allow_html=True)
st.subheader('Download your report')
st.write('- You can download the report by clicking on the **Download Report** link below')
st.write('- Please make sure to click the link within 30 seconds to initiate the download.')
st.write('- This time limit is set to optimize resource usage.')
st.write('- You don\'t need to change the name of the file.')
st.write('- If you fail to click the link within 30 seconds, you will need to perform the prediction again to generate and download the report.')
try:
self.__generate_report()
except:
st.warning('It seems like the report has not been downloaded. If you would like to access the report, please perform the prediction again.')