Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

3-app.py 8.9 KB

You have to be logged in to leave a comment. Sign In
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
  1. import os
  2. # If you dont want to use gpu
  3. os.environ["CUDA_VISIBLE_DEVICES"]="-1"
  4. import time
  5. import numpy as np
  6. import streamlit as st
  7. import cv2
  8. from skimage.transform import resize
  9. from tf_keras_vis.utils import normalize
  10. from tf_keras_vis.saliency import Saliency
  11. from tf_keras_vis.scorecam import ScoreCAM
  12. from tf_keras_vis.gradcam import Gradcam,GradcamPlusPlus
  13. from scipy.ndimage import gaussian_filter as gauss
  14. from utils import *
  15. import models
  16. import easygui
  17. #st.set_page_config(layout="wide")
  18. session_state = get(dirname=None,reset_model=True)
  19. #progress_bar = st.sidebar.progress(0)
  20. #status_text = st.sidebar.empty()
  21. #last_rows = np.random.randn(1, 1)
  22. #chart = st.line_chart(last_rows)
  23. #for i in range(1, 101):
  24. # new_rows = last_rows[-1, :] + np.random.randn(5, 1).cumsum(axis=0)
  25. ## status_text.text("%i%% Complete" % i)
  26. # chart.add_rows(new_rows)
  27. ## progress_bar.progress(i)
  28. # last_rows = new_rows
  29. # time.sleep(0.05)
  30. ##progress_bar.empty()
  31. ## Streamlit widgets automatically run the script from top to bottom. Since
  32. ## this button is not connected to any other logic, it just causes a plain
  33. ## rerun.
  34. #st.button("Rerun!")
  35. #my_bar = st.progress(0)
  36. #for percent_complete in range(100):
  37. # time.sleep(0.1)
  38. # my_bar.progress(percent_complete + 1)
  39. # st.write('{}%'.format((percent_complete+1)/100))
  40. def train():
  41. # data_path_opt = args.dataset
  42. # data_path_opt = st.text_input('Enter dataset path:', value='dataset/')
  43. # # import libraries
  44. # import tkinter as tk
  45. # from tkinter import filedialog
  46. # # Set up tkinter
  47. # root = tk.Tk()
  48. # root.withdraw()
  49. # # Make folder picker dialog appear on top of other windows
  50. # root.wm_attributes('-topmost', 1)
  51. # Folder picker button
  52. st.write('Please select the dataset directory:')
  53. clicked = st.button('Selected folder')
  54. dirname = None
  55. if clicked:
  56. dirname = easygui.diropenbox(title='dataset')
  57. # dirname = st.text_input('Selected folder:', dirname)
  58. # filedialog.askdirectory(master=root))
  59. session_state.dirname = dirname
  60. # st.subheader('You selected comedy.')
  61. # if st.button('Upload file'):
  62. #
  63. # print(easygui.fileopenbox())
  64. # data_path = session_state.dirname
  65. data_path = st.text_input('Selected model file:', session_state.dirname)
  66. model_opt = st.selectbox('Please select the architecture?',
  67. ('Model 1', 'Model 2'))
  68. lx = st.number_input('Image size', value=64)
  69. EPOCHS = st.number_input('Number of epochs', value=10)
  70. n_sample = 3
  71. restart = 1
  72. # EPOCHS = 2
  73. BS = 4
  74. # data_path = data_path_opt
  75. ly = lx
  76. pp = 4
  77. dpi = 150
  78. prefix = ''
  79. if model_opt=='Model 1':
  80. DEEP = 2
  81. elif model_opt=='Model 2':
  82. DEEP = 3
  83. if st.button('Train'):
  84. if data_path is None:
  85. st.write('You need to set the data directory first!')
  86. else:
  87. n_class,data = models.data_load(data_path,lx,ly,n_sample,pp,dpi,prefix,restart)
  88. models.train(data,n_class,DEEP,EPOCHS,BS,prefix,restart)
  89. # models.train(data_path,DEEP,EPOCHS,BS,lx,ly,n_sample,pp,dpi,prefix,restart)
  90. # session_state.reset_model
  91. # st.write('Training...')
  92. # progress_bar = st.progress(0)
  93. # status_text = st.empty()
  94. # chart = st.line_chart([1.])
  95. # for i in range(100):
  96. # # Update progress bar.
  97. # progress_bar.progress(i + 1)
  98. # new_rows = np.random.randn(1, 2)
  99. # # Update status text.
  100. # status_text.text('{}%'.format(100*(i+1)/100))
  101. # # Append data to the chart.
  102. # chart.add_rows([1/(i+1)])
  103. # # Pretend we're doing some computation that takes time.
  104. # time.sleep(0.02)
  105. # status_text.text('Done!')
  106. return
  107. def predict():
  108. cmap = plt.get_cmap('jet')
  109. lx,ly = 256,256
  110. int_map = {1: '06-class__2', 0: '04-class__1'}
  111. # {'04-class__1 EO': 0, '06-class__2 EO': 1} {0: '04-class__1 EO', 1: '06-class__2 EO'}
  112. # model_file = st.text_input('Enter model file:', value='none')
  113. st.write('Selected model file:')
  114. clicked = st.button('Model')
  115. if clicked:
  116. dirname = easygui.fileopenbox(title='model selection',filetypes=['*.h5'])
  117. # filedialog.askdirectory(master=root))
  118. session_state.dirname = dirname
  119. # st.subheader('You selected comedy.')
  120. # if st.button('Upload file'):
  121. #
  122. # print(easygui.fileopenbox())
  123. # model_file = session_state.dirname
  124. model_file = st.text_input('Selected model file:', session_state.dirname)
  125. uploaded_file = st.file_uploader("Choose a image file", type="jpg")
  126. option = st.selectbox(
  127. 'How would you like to choose as the attention analyzer?',
  128. ('Filter', 'Saliency', 'SmoothGrad', 'GradCAM', 'GradCAM++', 'ScoreCAM'))
  129. towcol = 1
  130. if uploaded_file is not None and model_file != 'Filter':
  131. # Convert the file to an opencv image.
  132. model = load_model(model_file)
  133. _,lx,ly,_ = model.layers[0].input_shape[0]
  134. if option=='Saliency':
  135. ## # Vanilla Saliency
  136. saliency = Saliency(model,
  137. model_modifier=model_modifier,
  138. clone=False)
  139. if option=='SmoothGrad':
  140. ## # SmoothGrad
  141. saliency = Saliency(model,
  142. model_modifier=model_modifier,
  143. clone=False)
  144. if option=='GradCAM':
  145. gradcam = Gradcam(model,
  146. model_modifier=model_modifier,
  147. clone=False)
  148. if option=='GradCAM++':
  149. gradcam = GradcamPlusPlus(model,
  150. model_modifier=model_modifier,
  151. clone=False)
  152. if option=='ScoreCAM':
  153. scorecam = ScoreCAM(model, model_modifier, clone=False)
  154. file_bytes = np.asarray(bytearray(uploaded_file.read()), dtype=np.uint8)
  155. img = cv2.imdecode(file_bytes, 1)
  156. img = resize(img,output_shape=(lx,ly))
  157. if img.ndim==3:
  158. img = np.mean(img,axis=-1)
  159. pp = filters(img,edd_method='sob')
  160. pp = pp-pp.min()
  161. pp = pp/pp.max()
  162. pp = pp[None,:,:,None]
  163. # st.image(pp,use_column_width=1)
  164. # st.write(pp.min(),pp.max())
  165. y_p = model.predict(pp)
  166. pind = np.argmax(y_p)
  167. st.markdown('**_CLASS_ {}**'.format(pind))
  168. if option=='Filter':
  169. att = pp[0,:,:,0]
  170. if option=='Saliency':
  171. loss = loss_maker(pind)
  172. att = saliency(loss,pp)[0]
  173. att = normalize(att)
  174. if option=='SmoothGrad':
  175. loss = loss_maker(pind)
  176. att = saliency(loss,pp,
  177. smooth_samples=20,
  178. smooth_noise=0.20)[0]
  179. att = normalize(att)
  180. if option=='GradCAM':
  181. loss = loss_maker(pind)
  182. att = gradcam(loss,pp,penultimate_layer=-1)[0]
  183. att = normalize(att)
  184. if option=='GradCAM++':
  185. loss = loss_maker(pind)
  186. att = gradcam(loss,pp,penultimate_layer=-1)[0]
  187. att = normalize(att)
  188. if option=='ScoreCAM':
  189. loss = loss_maker(pind)
  190. att = scorecam(loss,pp,penultimate_layer=-1)[0]
  191. att = normalize(att)
  192. if option!='Filter':
  193. att = gauss(att,3)
  194. att = cmap(att)
  195. att = att/att.max()
  196. # lbl = int_map[pind]
  197. img = img[:,:,None]
  198. img = np.concatenate(3*[img]+[np.ones(img.shape)],axis=-1)
  199. att[:,:,:3] = 0.7*img[:,:,:3]+0.3*att[:,:,:3]
  200. if towcol:
  201. col1, col2 = st.beta_columns(2)
  202. # with col1:
  203. col1.image(img, channels="RGB", caption=['Image is {}'.format(pind)],use_column_width=1)
  204. # with col2:
  205. col2.image(att, channels="RGB", caption=['Attention'],use_column_width=1)
  206. #
  207. else:
  208. showatt = st.checkbox('show attention')
  209. if showatt:
  210. st.image(att, channels="RGB", caption=['Attention'],use_column_width=1)
  211. else:
  212. st.image(img, channels="RGB", caption=['Image is {}'.format(pind)],use_column_width=1)
  213. # Now do something with the image! For example, let's display it:
  214. # st.image([img,pred], channels="BGR", width=300, caption=['Image','Attention map'])
  215. return
  216. st.title('Model training and prediction application.')
  217. mode = st.radio(
  218. "Please choose the procedure:",
  219. ('Train a model', 'Predict with a model'))
  220. if mode == 'Train a model':
  221. st.subheader('You are going to train a model.')
  222. train()
  223. elif mode == 'Predict with a model':
  224. st.subheader("You are going to predict with a trained model.")
  225. predict()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...