Advertisement
max2201111

ok posledni VK

May 26th, 2024
536
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 45.24 KB | Science | 0 0
  1. #Navod na pouziti, Mgr. Hynek Mlčoušek, v Brne 2.5.2024
  2. #Ulozte do lokalniho souboru u sebe na PC data tohoto tvaru vzdy ukoncene 0 ci 1 (jde o uceni s ucitelem: 1 = nemocny, 0 = prezil/zdravy, ve vystupu bude zelena znacit 0, cervena 1)  a bez znaku #; pozor na ","
  3.  
  4. # [ [23.657800719276743,18.859916797201468,0],
  5. # [22.573729142097473,17.96922325097786,0],
  6. # [32.55342396968757,29.463651408558803,0],
  7. # [6.718035041529263,25.704665468161718,1],
  8. # [14.401918566243225,16.770856492924658,0],
  9. # [17.457907312962234,21.76521470574044,0],
  10. # [20.02796946568093,73.45445954770891,1],
  11. # [30.295138369778076,62.901112886193246,1],
  12. # [15.128977804449633,32.40267702110393,0],
  13. # [30.179457395820013,58.982492125646104,1],
  14. # [28.01649701854089,63.92781357637711,1],
  15. # [16.791838457871147,42.33482314089884,0],
  16. # [10.583694293380976,19.61926728942497,0],
  17. # [26.634447074406467,91.96624817360987,1],
  18. # [26.217868623367643,36.400293587062976,0],
  19. # [17.689396788624936,60.79797114006423,1],
  20. # [33.17193822527976,66.75277364959176,1],
  21. # [23.793952755709153,22.57501437360518,0]]
  22.  
  23. #kliknete na cerne tlacitko s trojuhelnickem vlevo nahore
  24. #pod kodem se objevi moznost spustit dialogove okenko, kliknete na nej
  25. #soubor, ktery mate z bodu vyse vyberte a nahrajte
  26. #Najdete v tomto kodu retezec:
  27. ###ZDE VLOZTE DATA OD NOVYCH PACIENTU
  28.  
  29. #Vlozte do pole
  30. # new_persons_results = []
  31. # data o nekolika malo novych pacientech bez ukoncovaci 0 a 1, ale se stejnym poctem sloupcu jako ma soubor z Vaseho lokalniho disku, vyse by tedy toto bylo rovno 2
  32. #kod vyhodi hned po natrenovani, (jehoz prubeh muzete sledovat na modre progres bare) pro kazdy radek z new_persons_results bilo-sedo-cerne ctverecky vznikle z normalizace poskytnutych dat a ukoncovaci ctverecek cerveny pripadne zeleny
  33. #zaroven s tim se vypise realne cislo mezi 0 a 1 znacici jak moc je pacient zdravy (blizke 0) ci nemocny (blizke 1)
  34. #cisla uprostred pak indikuji zadany oranzovy semafor.
  35. #je na lekarich nastavit tresholdy (tedy pravdepodobnosti: cisla mezi 0 a 1) ktere pak daji zaver, zda je pacient cerveny, oranzovy ci zeleny
  36.  
  37. # prosim o komnetare a vysledky na realnych datech, je zadouci aby radku v matici, tedy pacientu byly stovky a sloupcu desitky
  38. # Moznosti vyuziti: onkologicka diagnoza vs. zdrava kontorlni skupina, diabetes (pritomnost/nepritomnost), testovani noveho leku oproti placebu atd.
  39.  
  40. #kod zaroven vyhodi confusion matici, tedy mozne True Negative a False Positive plus spravne zarazene hodnoty spolu s presnosti,F1 score recall atd.
  41. #poznamka ke kodu: jde o epxerimentalni verzi, ktera krome skutecne potrebneho kodu obsahuje ladici informace, ruzne duplicity, nadbytecne prikazy atd.
  42. # Na uvod behu programu se pro kontorlu vypise poskytnuta matice a jeji normalizovana verze, je treba sjet jezdcem napravo nize na obrazky a dalsi vystupy
  43.  
  44. #Dekuji profesoru Petru Dostalovi za namet k teto praci a poskytnuta data, byt je potreba mit data realna
  45.  
  46. import numpy as np
  47. import matplotlib.pyplot as plt
  48. import tensorflow as tf
  49. from tqdm import tqdm
  50.  
  51.  
  52. from IPython.display import display
  53. from IPython.display import Javascript
  54. display(Javascript('IPython.OutputArea.auto_scroll_threshold = 9999;'))
  55.  
  56. label_colors = {0: [0, 128, 0], 1: [255, 0, 0]}
  57. label_colors_testing = {0: [0, 128, 0], 1: [255, 0, 0]}
  58.  
  59.  
  60. %matplotlib inline
  61.  
  62.  
  63.  
  64. # Function to create images based on predictions
  65. def create_image(data, predictions):
  66.     num_rows, num_columns = len(data), len(data[0])
  67.     image = np.zeros((num_rows, num_columns + 1, 3), dtype=np.uint8)
  68.  
  69.     for i in range(num_rows):
  70.         for j in range(num_columns):
  71.             pixel_value = int(np.interp(data[i][j], [np.min(data), np.max(data)], [0, 255]))
  72.             image[i, j] = np.array([pixel_value] * 3)
  73.  
  74.         # Create a gradient based on the normalized values
  75.         gradient_value = int(np.interp(predictions[i], [0, 1], [0, 255]))
  76.         image[i, -1] = np.array([gradient_value] * 3)
  77.  
  78.     return image
  79.  
  80. def create_image(data, predictions):
  81.     num_rows, num_columns = len(data), len(data[0])
  82.     image = np.zeros((num_rows, num_columns + 1, 3), dtype=np.uint8)
  83.  
  84.     for i in range(num_rows):
  85.         for j in range(num_columns):
  86.             pixel_value = int(np.interp(data[i][j], [np.min(data), np.max(data)], [0, 255]))
  87.             image[i, j] = np.array([pixel_value] * 3)
  88.  
  89.         # Use red for class 0 and green for class 1
  90.         if predictions[i] == 0:
  91.             image[i, -1] = np.array([255, 0, 0])  # Red
  92.         elif predictions[i] == 1:
  93.             image[i, -1] = np.array([0, 128, 0])  # Green
  94.  
  95.     return image
  96.  
  97. def create_image(data, predictions, label_colors):
  98.     num_rows, num_columns = len(data), len(data[0])
  99.     image = np.zeros((num_rows, num_columns + 1, 3), dtype=np.uint8)
  100.  
  101.     for i in range(num_rows):
  102.         for j in range(num_columns):
  103.             pixel_value = int(np.interp(data[i][j], [np.min(data), np.max(data)], [0, 255]))
  104.             image[i, j] = np.array([pixel_value] * 3)
  105.  
  106.         # Use the specified color for the last column based on the label
  107.         image[i, -1] = label_colors[predictions[i]]
  108.  
  109.     return image
  110.  
  111. # def create_imageN(data, predictions, label_colors=None):
  112. #     num_rows, num_columns = len(data), len(data[0])
  113. #     image = np.zeros((num_rows, num_columns + 1, 3), dtype=np.uint8)
  114.  
  115. #     for i in range(num_rows):
  116. #         for j in range(num_columns):
  117. #             # Map data values to the full range of 0 to 255
  118. #             pixel_value = int(np.interp(data[i][j], [np.min(data), np.max(data)], [0, 255]))
  119. #             image[i, j] = np.array([pixel_value] * 3)
  120.  
  121. #         # Use the specified color for the last column based on the label
  122. #         if label_colors is not None:
  123. #             image[i, -1] = label_colors[predictions[i]]
  124. #         else:
  125. #             # If label_colors is not provided, set the last column to grayscale
  126. #             pixel_value = int(np.interp(predictions[i], [0, 1], [0, 255]))
  127. #             image[i, -1] = np.array([pixel_value] * 3)
  128.  
  129. #     return image
  130.  
  131. # def create_imageN(data, predictions, label_colors=None):
  132. #     num_rows, num_columns = len(data), len(data[0])
  133. #     image = np.zeros((num_rows, num_columns + 1, 3), dtype=np.uint8)
  134.  
  135. #     for i in range(num_rows):
  136. #         for j in range(num_columns):
  137. #             # Map data values to the full range of 0 to 255
  138. #             pixel_value = int(np.interp(data[i][j], [np.min(data), np.max(data)], [0, 255]))
  139. #             image[i, j] = np.array([pixel_value] * 3)
  140.  
  141. #         # Use the specified color for the last column based on the label
  142. #         if label_colors is not None:
  143. #             image[i, -1] = label_colors[predictions[i]]
  144. #         else:
  145. #             # If label_colors is not provided, set the last column to grayscale
  146. #             pixel_value = int(np.interp(predictions[i], [np.min(data), np.max(data)], [0, 255]))
  147. #             image[i, -1] = np.array([pixel_value] * 3)
  148.  
  149. #     return image
  150.  
  151. # def create_imageN(data, predictions, label_colors=None):
  152. #     num_rows, num_columns = len(data), len(data[0])
  153. #     image = np.zeros((num_rows, num_columns + 1, 3), dtype=np.uint8)
  154.  
  155. #     for i in range(num_rows):
  156. #         for j in range(num_columns - 1):  # Exclude the last column for now
  157. #             # Map data values to the full range of 0 to 255
  158. #             pixel_value = int(np.interp(data[i][j], [np.min(data[:, j]), np.max(data[:, j])], [0, 255]))
  159. #             image[i, j] = np.array([pixel_value] * 3)
  160.  
  161. #         # Use the specified color for the last column based on the label
  162. #         if label_colors is not None:
  163. #             image[i, -1] = label_colors[predictions[i]]
  164. #         else:
  165. #             # If label_colors is not provided, set the last column to grayscale
  166. #             pixel_value = int(np.interp(predictions[i], [0, 1], [0, 255]))
  167. #             image[i, -1] = np.array([pixel_value] * 3)
  168.  
  169. #     return image
  170.  
  171.  
  172. # def create_imageN(data, predictions, label_colors=None):
  173. #     num_rows, num_columns = len(data), len(data[0])
  174. #     image = np.zeros((num_rows, num_columns + 1, 3), dtype=np.uint8)
  175.  
  176. #     data_array = np.array(data)  # Convert data to a NumPy array
  177.  
  178. #     for i in range(num_rows):
  179. #         for j in range(num_columns - 1):  # Exclude the last column for now
  180. #             # Map data values to the full range of 0 to 255
  181. #             pixel_value = int(np.interp(data_array[i, j], [np.min(data_array[:, j]), np.max(data_array[:, j])], [0, 255]))
  182. #             image[i, j] = np.array([pixel_value] * 3)
  183.  
  184. #         # Use the specified color for the last column based on the label
  185. #         if label_colors is not None:
  186. #             image[i, -1] = label_colors[predictions[i]]
  187. #         else:
  188. #             # If label_colors is not provided, set the last column to grayscale
  189. #             pixel_value = int(np.interp(predictions[i], [0, 1], [0, 255]))
  190. #             image[i, -1] = np.array([pixel_value] * 3)
  191.  
  192. #     return image
  193.  
  194. # def create_imageN(data, predictions, label_colors=None):
  195. #     num_rows, num_columns = len(data), len(data[0])
  196. #     image = np.zeros((num_rows, num_columns + 1, 3), dtype=np.uint8)
  197.  
  198. #     data_array = np.array(data)  # Convert data to a NumPy array
  199.  
  200. #     for i in range(num_rows):
  201. #         for j in range(num_columns - 1):  # Exclude the last column for now
  202. #             # Map data values to the full range of 0 to 255
  203. #             pixel_value = int(np.interp(data_array[i, j], [np.min(data_array[:, j]), np.max(data_array[:, j])], [0, 255]))
  204. #             image[i, j] = np.array([pixel_value] * 3)
  205.  
  206. #         # Use the specified color for the last column based on the label
  207. #         if label_colors is not None:
  208. #             image[i, -1] = label_colors[predictions[i]]
  209. #         else:
  210. #             # If label_colors is not provided, set the last column to grayscale
  211. #             pixel_value = int(np.interp(predictions[i], [0, 1], [0, 255]))
  212. #             image[i, -1] = np.array([pixel_value] * 3)
  213.  
  214. #     # Now, normalize the last column separately to achieve grayscale
  215. #     min_pixel_value = np.min(image[:, -1])
  216. #     max_pixel_value = np.max(image[:, -1])
  217. #     for i in range(num_rows):
  218. #         pixel_value = int(np.interp(image[i, -1], [min_pixel_value, max_pixel_value], [0, 255]))
  219. #         image[i, -1] = np.array([pixel_value] * 3)
  220.  
  221. #     return image
  222.  
  223. # def create_imageN(data, predictions, label_colors=None):
  224. #     num_rows, num_columns = len(data), len(data[0])
  225. #     image = np.zeros((num_rows, num_columns + 1, 3), dtype=np.uint8)
  226.  
  227. #     for i in range(num_rows):
  228. #         for j in range(num_columns):
  229. #             # Map data values to the full range of 0 to 255
  230. #             pixel_value = int(np.interp(data[i][j], [np.min(data), np.max(data)], [0, 255]))
  231. #             image[i, j] = np.array([pixel_value] * 3)
  232.  
  233. #         # Now, normalize the last column separately to achieve grayscale
  234.  
  235.  
  236. #         min_pixel_value = np.min(data[:, -1])
  237. #         max_pixel_value = np.max(data[:, -1])
  238. #         pixel_value = int(np.interp(data[i][-1], [min_pixel_value, max_pixel_value], [0, 255]))
  239.  
  240. #         # Use the specified color for the last column based on the label
  241. #         if label_colors is not None:
  242. #             image[i, -1] = label_colors[predictions[i]]
  243.  
  244. #     return image
  245.  
  246. # def create_imageN(data, predictions, label_colors=None):
  247. #     num_rows, num_columns = len(data), len(data[0])
  248. #     image = np.zeros((num_rows, num_columns + 1, 3), dtype=np.uint8)
  249.  
  250. #     for i in range(num_rows):
  251. #         for j in range(num_columns):
  252. #             # Map data values to the full range of 0 to 255
  253. #             pixel_value = int(np.interp(data[i][j], [np.min(data), np.max(data)], [0, 255]))
  254. #             image[i, j] = np.array([pixel_value] * 3)
  255.  
  256. #         # Normalize the last column separately to achieve grayscale
  257. #         min_pixel_value = np.min(data[i])
  258. #         max_pixel_value = np.max(data[i])
  259. #         pixel_value = int(np.interp(data[i][-1], [min_pixel_value, max_pixel_value], [0, 255]))
  260. #         image[i, -1] = np.array([pixel_value] * 3)
  261.  
  262. #         # Use the specified color for the last column based on the label
  263. #         if label_colors is not None:
  264. #             image[i, -1] = label_colors[predictions[i]]
  265.  
  266. #     return image
  267.  
  268.  
  269. # def create_imageN(data, predictions, label_colors=None):
  270. #     num_rows, num_columns = len(data), len(data[0])
  271. #     image = np.zeros((num_rows, num_columns + 1, 3), dtype=np.uint8)
  272.  
  273. #     # Normalize the first two columns independently
  274. #     for j in range(2):
  275. #         min_pixel_value = np.min(data[:, j])
  276. #         max_pixel_value = np.max(data[:, j])
  277. #         for i in range(num_rows):
  278. #             pixel_value = int(np.interp(data[i][j], [min_pixel_value, max_pixel_value], [0, 255]))
  279. #             image[i, j] = np.array([pixel_value] * 3)
  280.  
  281. #     # Normalize the last column separately to achieve grayscale
  282. #     min_pixel_value = np.min(data[:, -1])
  283. #     max_pixel_value = np.max(data[:, -1])
  284. #     for i in range(num_rows):
  285. #         pixel_value = int(np.interp(data[i][-1], [min_pixel_value, max_pixel_value], [0, 255]))
  286. #         image[i, -1] = np.array([pixel_value] * 3)
  287.  
  288. #         # Use the specified color for the last column based on the label
  289. #         if label_colors is not None:
  290. #             image[i, -1] = label_colors[predictions[i]]
  291.  
  292. #     return image
  293.  
  294. # def create_imageN(data, predictions, label_colors=None):
  295. #     # Convert data to a NumPy array
  296. #     data = np.array(data)
  297.  
  298. #     num_rows, num_columns = data.shape
  299. #     image = np.zeros((num_rows, num_columns + 1, 3), dtype=np.uint8)
  300.  
  301. #     # Normalize the first two columns independently
  302. #     for j in range(2):
  303. #         min_pixel_value = np.min(data[:, j])
  304. #         max_pixel_value = np.max(data[:, j])
  305. #         for i in range(num_rows):
  306. #             pixel_value = int(np.interp(data[i][j], [min_pixel_value, max_pixel_value], [0, 255]))
  307. #             image[i, j] = np.array([pixel_value] * 3)
  308.  
  309. #     # Normalize the last column separately to achieve grayscale
  310. #     min_pixel_value = np.min(data[:, -1])
  311. #     max_pixel_value = np.max(data[:, -1])
  312. #     for i in range(num_rows):
  313. #         pixel_value = int(np.interp(data[i][-1], [min_pixel_value, max_pixel_value], [0, 255]))
  314. #         image[i, -1] = np.array([pixel_value] * 3)
  315.  
  316. #         # Use the specified color for the last column based on the label
  317. #         if label_colors is not None:
  318. #             image[i, -1] = label_colors[predictions[i]]
  319.  
  320. #     return image
  321.  
  322.  
  323. # def create_imageN(data, predictions, label_colors=None):
  324. #     # Convert data to a NumPy array
  325. #     data = np.array(data)
  326.  
  327. #     num_rows, num_columns = data.shape
  328. #     image = np.zeros((num_rows, num_columns + 1, 3), dtype=np.uint8)
  329.  
  330. #     # Normalize the first two columns independently
  331. #     for j in range(2):
  332. #         min_pixel_value = np.min(data[:, j])
  333. #         max_pixel_value = np.max(data[:, j])
  334. #         for i in range(num_rows):
  335. #             pixel_value = int(np.interp(data[i][j], [min_pixel_value, max_pixel_value], [0, 255]))
  336. #             image[i, j] = np.array([pixel_value] * 3)
  337.  
  338. #     # Normalize the last column separately to achieve grayscale
  339. #     min_pixel_value_last = np.min(data[:, -1])
  340. #     max_pixel_value_last = np.max(data[:, -1])
  341. #     for i in range(num_rows):
  342. #         pixel_value_last = int(np.interp(data[i][-1], [min_pixel_value_last, max_pixel_value_last], [0, 255]))
  343. #         image[i, -1] = np.array([pixel_value_last] * 3)
  344.  
  345. #         # Use the specified color for the last column based on the label
  346. #         if label_colors is not None:
  347. #             image[i, -1] = label_colors[predictions[i]]
  348.  
  349. #     return image
  350.  
  351. # def create_imageN(data, predictions, label_colors=None):
  352. #     image_training = np.zeros((num_training_rows, len(X_train[0]) + 1, 3), dtype=np.uint8)
  353.  
  354.  
  355. #     print("**************************",num_training_rows,"*******************")
  356.  
  357. #     min_pixel_value = np.min(X_train_normalized)
  358. #     max_pixel_value = np.max(X_train_normalized)
  359.  
  360. #     # Populate image_training with consistent gray and red/green colors based on the labels in the last column
  361. #     # for i, label in enumerate(y_train):
  362. #     #     for j in range(len(X_train[0])
  363. #     #         pixel_value = int(np.interp(X_train_normalized[i][j], [min_pixel_value, max_pixel_value], [0, 255]))
  364. #     #         image_training[i, j] = np.array([pixel_value] * 3)
  365. #     #         image_training[i, -1] = np.array([128, 128, 128])
  366. #     #     if label == 0:
  367. #     #         image_training[i, -1] = np.array([0, 128, 0])
  368. #     #     elif label == 1:
  369. #     #         image_training[i, -1] = np.array([255, 0, 0])
  370.  
  371.  
  372.  
  373. #     # Populate image_training with consistent gray and red/green colors based on the labels in the last column
  374. #     for i, label in enumerate(y_train):
  375. #         for j in range(len(X_train[0])):
  376. #             pixel_value = int(np.interp(X_train_normalized[i][j], [min_pixel_value, max_pixel_value], [0, 255]))
  377. #             image_training[i, j] = np.array([pixel_value] * 3)
  378. #         image_training[i, -1] = np.array([128, 128, 128])
  379. #         if label == 0:
  380. #             image_training[i, -1] = np.array([0, 128, 0])
  381. #         elif label == 1:
  382. #             image_training[i, -1] = np.array([255, 0, 0])
  383.  
  384.  
  385. #     return image_training
  386.  
  387.  
  388.  
  389.  
  390.  
  391.  
  392.  
  393.  
  394. # def create_imageN(data, predictions, label_colors=None):
  395. #     num_training_rows = 1  # Set the number of rows to 1
  396. #     image_training = np.zeros((num_training_rows, len(X_train[0]) + 1, 3), dtype=np.uint8)
  397.  
  398. #     min_pixel_value = np.min(X_train_normalized)
  399. #     max_pixel_value = np.max(X_train_normalized)
  400.  
  401. #     # Populate image_training with consistent gray and red/green colors based on the labels in the last column
  402. #     for j in range(len(X_train[0])):
  403. #         pixel_value = int(np.interp(data[0][j], [min_pixel_value, max_pixel_value], [0, 255]))
  404. #         image_training[0, j] = np.array([pixel_value] * 3)
  405.  
  406. #     image_training[0, -1] = np.array([128, 128, 128])  # Set a consistent gray background
  407.  
  408. #     label = y_train[0]
  409. #     if label == 0:
  410. #         image_training[0, -1] = np.array([0, 128, 0])  # Green for label 0
  411. #     elif label == 1:
  412. #         image_training[0, -1] = np.array([255, 0, 0])  # Red for label 1
  413.  
  414. #     return image_training
  415.  
  416. def create_imageN(data, predictions, label_colors=None):
  417.     num_training_rows = len(data)  # Set the number of rows based on the data
  418.     num_columns = len(data[0])
  419.  
  420.     image_training = np.zeros((num_training_rows, num_columns + 1, 3), dtype=np.uint8)
  421.  
  422.     min_pixel_value = np.min(X_train_normalized)
  423.     max_pixel_value = np.max(X_train_normalized)
  424.  
  425.     for i in range(num_training_rows):
  426.         # Normalize the first columns independently
  427.         for j in range(num_columns):
  428.             pixel_value = int(np.interp(data[i][j], [min_pixel_value, max_pixel_value], [0, 255]))
  429.             image_training[i, j] = np.array([pixel_value] * 3)
  430.  
  431.         # Normalize the last column separately to achieve grayscale
  432.         pixel_value_last = int(np.interp(data[i][-1], [min_pixel_value, max_pixel_value], [0, 255]))
  433.         image_training[i, -1] = np.array([pixel_value_last] * 3)
  434.  
  435.         # Use the specified color for the last column based on the label
  436.         if label_colors is not None:
  437.             image_training[i, -1] = label_colors[predictions[i]]
  438.  
  439.     return image_training
  440.  
  441.  
  442.  
  443.  
  444. # Load data from a file
  445. #file_path = 'C:/Users/Hynek/Desktop/example4.txt'
  446. from google.colab import files
  447. uploaded = files.upload()
  448.  
  449. # Tento kód otevře dialogové okno pro výběr souboru z vašeho počítače.
  450. import io
  451. import pandas as pd
  452.  
  453. # Předpokládáme, že jste nahráli CSV soubor
  454. for fn in uploaded.keys():
  455.   print('User uploaded file "{name}" with length {length} bytes'.format(
  456.       name=fn, length=len(uploaded[fn])))
  457.   path = io.BytesIO(uploaded[fn])  # Pro soubory, které potřebují být čteny jako binární objekty
  458.   df = pd.read_csv(path)
  459.   print(df.head())  # Vypíše prvních pět řádků DataFrame
  460.  
  461.  
  462. all_results = []
  463. #with open(file_path, 'r') as file:
  464. #    file_content = file.read()
  465.  
  466. # Execute the content as Python code
  467. ##exec(file_content)
  468.  
  469. import os
  470. import shutil
  471. import ast
  472.  
  473. for filename in uploaded.keys():
  474.     original_path = f"/content/{filename}"
  475.     destination_path = os.path.join("/content/", "/content/DATA2")
  476.     shutil.move(original_path, destination_path)
  477.     print(f"Soubor {filename} byl přesunut do {destination_path}")
  478.  
  479. file_path = '/content/DATA2'  # Cesta k souboru
  480. with open(file_path, 'r') as file:
  481.     code = file.read()
  482.  
  483. A_list = ast.literal_eval(code)
  484.  
  485.  
  486. # Převod na NumPy pole
  487. A = np.array(A_list)
  488.  
  489. #exec(code)
  490.  
  491. # Now, all_results contains lists corresponding to each row in the CSV file
  492. ##print(all_results)
  493.  
  494. # Assign values to variables dynamically based on the rows of matrix A
  495. for i, row in enumerate(A, start=1):
  496.     globals()[f"person{i}_results"] = list(row)
  497.  
  498. # Print the assigned variables
  499. for i in range(1, len(A) + 1):
  500.   #  print(f"person{i}_results {globals()[f'person{i}_results']}")
  501.     all_results.append(f"person{i}_results")
  502. ##print(all_results)
  503.  
  504.  
  505.  
  506. result_variables = []
  507.  
  508. # Loop through the variable names and get the corresponding variables using globals()
  509. for var_name in all_results:
  510.     result_variables.append(globals()[var_name])
  511.  
  512. # Now, result_variables contains the variables with names specified in variable_names
  513. #print(result_variables)
  514.  
  515. all_results = result_variables
  516. new_persons_results = result_variables
  517.  
  518.  
  519. # # Define the blood test results for sixteen persons
  520. # person1_results = [80, 90, 100, 125, 120, 0]
  521. # person2_results = [95, 105, 115, 110, 135, 1]
  522. # person3_results = [110, 120, 130, 140, 150, 0]
  523. # person4_results = [100, 110, 120, 130, 140, 1]
  524. # person5_results = [105, 115, 100, 105, 110, 0]
  525. # person6_results = [90, 110, 115, 95, 120, 1]
  526. # person7_results = [116, 99, 106, 105, 119, 0]
  527. # person8_results = [111, 93, 118, 118, 107, 1]
  528. # person9_results = [107, 97, 105, 119, 98, 0]
  529. # person10_results = [92, 108, 90, 117, 111, 1]
  530. # person11_results = [118, 105, 103, 118, 99, 0]
  531. # person12_results = [97, 115, 101, 101, 113, 1]
  532. # person13_results = [95, 111, 93, 112, 120, 0]
  533. # person14_results = [100, 112, 118, 109, 103, 1]
  534. # person15_results = [113, 91, 94, 93, 99, 0]
  535. # person16_results = [103, 92, 95, 110, 98, 1]
  536.  
  537. # # Combine the results into a list
  538. # all_results = [person1_results, person2_results, person3_results, person4_results,
  539. #                person5_results, person6_results, person7_results, person8_results,
  540. #                person9_results, person10_results, person11_results, person12_results,
  541. #                person13_results, person14_results, person15_results, person16_results]
  542.  
  543.  
  544. # #all_results = [person1_results, person2_results]
  545.  
  546.  
  547. # Extract the last column (0 or 1) as labels
  548. labels = [results[-1] for results in all_results]
  549.  
  550. # Remove the last column from the dataset
  551. data = [results[:-1] for results in all_results]
  552.  
  553. # Define the number of rows for training and testing
  554. num_training_rows = 100
  555. num_testing_rows = 100
  556.  
  557. # Split the data into training and testing datasets
  558. #X_train, X_test, y_train, y_test = data[:num_training_rows], data[-num_testing_rows:], labels[:num_training_rows], labels[-num_testing_rows:]
  559.  
  560. X_train, X_test, y_train, y_test = data[:num_training_rows], data[:num_testing_rows], labels[:num_training_rows], labels[:num_testing_rows]
  561.  
  562.  
  563. # Normalize the training data
  564. min_values = np.min(X_train, axis=0)
  565. max_values = np.max(X_train, axis=0)
  566. X_train_normalized = (X_train - min_values) / (max_values - min_values)
  567.  
  568.  
  569. # Normalize the training data
  570. min_values = np.min(X_train, axis=0)
  571. max_values = np.max(X_train, axis=0)
  572. X_train_normalized = (X_train - min_values) / (max_values - min_values)
  573.  
  574. # Normalize the testing data using the min and max values of the training data
  575. X_test_normalized = (X_test - min_values) / (max_values - min_values)
  576.  
  577.  
  578. # Print normalized training data
  579. print("Normalized Training Data:")
  580. print(X_train_normalized)
  581. print("Adenormalized",X_train_normalized*(max_values - min_values)+min_values,"Bdenormalized")
  582.  
  583. # Define a simple neural network model
  584. # model = tf.keras.Sequential([
  585. #     tf.keras.layers.Dense(128, activation='relu', input_shape=(len(X_train[0]),)),
  586. #     tf.keras.layers.Dense(64, activation='relu'),
  587. #     tf.keras.layers.Dense(1, activation='sigmoid')
  588. # ])
  589.  
  590. # # Compile the model
  591. # model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
  592.  
  593.  
  594. import tensorflow as tf
  595.  
  596. # Vylepšený model
  597. model = tf.keras.Sequential([
  598.     tf.keras.layers.Dense(256, activation='relu', input_shape=(len(X_train[0]),)),
  599.     tf.keras.layers.Dropout(0.3),
  600.     tf.keras.layers.Dense(128, activation='relu'),
  601.     tf.keras.layers.Dropout(0.3),
  602.     tf.keras.layers.Dense(64, activation='relu'),
  603.     tf.keras.layers.Dropout(0.3),
  604.     tf.keras.layers.Dense(1, activation='sigmoid')
  605. ])
  606.  
  607. # Použití Adam optimizer s learning rate schedulerem
  608. lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(
  609.     initial_learning_rate=1e-3,
  610.     decay_steps=10000,
  611.     decay_rate=0.9
  612. )
  613. optimizer = tf.keras.optimizers.Adam(learning_rate=lr_schedule)
  614.  
  615. # Kompilace modelu
  616. model.compile(optimizer=optimizer, loss='binary_crossentropy', metrics=['accuracy'])
  617.  
  618.  
  619. # Lists to store accuracy values
  620. accuracy_history = []
  621.  
  622. # Create images for the training data
  623. image_training = np.zeros((num_training_rows, len(X_train[0]) + 1, 3), dtype=np.uint8)
  624.  
  625.  
  626. min_pixel_value = np.min(X_train_normalized)
  627. max_pixel_value = np.max(X_train_normalized)
  628.  
  629. # Populate image_training with consistent gray and red/green colors based on the labels in the last column
  630. # for i, label in enumerate(y_train):
  631. #     for j in range(len(X_train[0])
  632. #         pixel_value = int(np.interp(X_train_normalized[i][j], [min_pixel_value, max_pixel_value], [0, 255]))
  633. #         image_training[i, j] = np.array([pixel_value] * 3)
  634. #         image_training[i, -1] = np.array([128, 128, 128])
  635. #     if label == 0:
  636. #         image_training[i, -1] = np.array([0, 128, 0])
  637. #     elif label == 1:
  638. #         image_training[i, -1] = np.array([255, 0, 0])
  639.  
  640.  
  641.  
  642. # Populate image_training with consistent gray and red/green colors based on the labels in the last column
  643. for i, label in enumerate(y_train):
  644.     for j in range(len(X_train[0])):
  645.         pixel_value = int(np.interp(X_train_normalized[i][j], [min_pixel_value, max_pixel_value], [0, 255]))
  646.         image_training[i, j] = np.array([pixel_value] * 3)
  647.     image_training[i, -1] = np.array([128, 128, 128])
  648.     if label == 0:
  649.         image_training[i, -1] = np.array([0, 128, 0])
  650.     elif label == 1:
  651.         image_training[i, -1] = np.array([255, 0, 0])
  652.  
  653.  
  654.  
  655.  
  656.  
  657.  
  658. from tqdm.notebook import tqdm_notebook
  659.  
  660.  
  661. ###ZDE VLOZTE DATA OD NOVYCH PACIENTU
  662.  
  663.  
  664. # Train the model for 400 epochs
  665. epochs = 1387
  666. # Assuming 'new_persons_results' is a list of new persons, where each person is represented as a list of features
  667. new_persons_results = [
  668.    # [101, 112],
  669.    # [0.54422416, 0.02778176],
  670.    # [22.57372914, 17.96922325],
  671. #    [22.57372914, 17.96922325]
  672.     # Add more new persons as needed
  673. #          [23.65780072, 18.8599168 ],
  674. #          [22.57372914, 17.96922325],
  675. #          [32.55342397, 29.46365141],
  676. #          [ 6.71803504, 25.70466547],
  677. #          [ 6.71803504, 25.70466547],
  678. #          [14.40191857, 16.77085649],
  679. #          [17.45790731, 21.76521471],
  680. #          [2110.02796947, 73.45445955],
  681. #          [30.29513837, 62.90111289],
  682. #          [15.1289778,  32.40267702],
  683.  
  684.  [23.65780072, 18.8599168 ],
  685.  [22.57372914, 17.96922325],
  686.  [32.55342397, 29.46365141],
  687.  [ 6.71803504, 25.70466547],
  688.  [14.40191857, 16.77085649],
  689.  [17.45790731, 21.76521471],
  690.  [20.02796947, 73.45445955],
  691.  [26.2042, 10.6782],
  692.  [35.7258, 82.8027],
  693.  
  694. # [23.657800719276743,18.859916797201468,0],
  695. # [22.573729142097473,17.96922325097786,0],
  696. # [32.55342396968757,29.463651408558803,0],
  697. # [6.718035041529263,25.704665468161718,2],
  698. # [14.401918566243225,16.770856492924658,0],
  699. # [17.457907312962234,21.76521470574044,0],
  700. # [20.02796946568093,73.45445954770891,2],  
  701.  
  702. ]
  703.  
  704. import sys
  705.  
  706. for epoch in tqdm_notebook(range(epochs)):
  707.     history = model.fit(X_train_normalized, np.array(y_train), epochs=1, verbose=0, shuffle=True)
  708.     accuracy_history.append(history.history['accuracy'][0])
  709.  
  710.     if epoch == 1:
  711.         # Normalize the testing data
  712.         X_test_normalized = (X_test - min_values) / (max_values - min_values)
  713.         y_pred_after_2nd_epoch = model.predict(X_test_normalized)
  714.         y_pred_binary_after_2nd_epoch = [1 if pred >= 0.5 else 0 for pred in y_pred_after_2nd_epoch]
  715.         image_testing_before_2nd_epoch = create_image(X_test_normalized, y_pred_binary_after_2nd_epoch, label_colors_testing)
  716.  
  717.     if epoch >= epochs-1:
  718.         print(f"HERE HERE Epoch: {epoch}, Epochs: {epochs}\n")
  719.         sys.stdout.flush()
  720.  
  721.         # Iterate through new persons
  722.         for idx, personNEW_results in enumerate(new_persons_results, start=0):
  723.             # Ensure that personNEW_results has the same number of features as the model expects
  724.             assert len(personNEW_results) == len(X_train[0]), "Mismatch in the number of features."
  725.  
  726.             personNEW_results_normalized = (np.array(personNEW_results) - min_values) / (max_values - min_values)
  727.  
  728.             personNEW_prediction = model.predict(np.array([personNEW_results_normalized]))
  729.             personNEW_label = 1 if personNEW_prediction >= 0.5 else 0
  730.             y_pred_after_50_epochs = model.predict(X_test_normalized)
  731.             y_pred_binary_after_50_epochs = [1 if pred >= 0.5 else 0 for pred in y_pred_after_50_epochs]
  732.             image_testing_after_50_epochs = create_image(X_test_normalized, y_pred_binary_after_50_epochs, label_colors_testing)
  733.  
  734.             # Create an image for the new person
  735.             image_personNEW = create_imageN([personNEW_results_normalized], [personNEW_label], label_colors)
  736.  
  737.             # Display the images
  738.             plt.figure(figsize=(5, 5))
  739.             plt.imshow(image_personNEW)
  740.             plt.title(f"New Person {idx}\nLabel: {personNEW_label}, Prediction: {personNEW_prediction},personNEW_results: {personNEW_results}")
  741.             plt.axis("off")
  742.             plt.show()
  743.  
  744.  
  745. # Display the images
  746. plt.figure(figsize=(25, 15))
  747. plt.subplot(2, 2, 1)
  748. plt.imshow(image_training)
  749. plt.title("Training Data")
  750. plt.axis("off")
  751.  
  752. plt.subplot(2, 2, 2)
  753. plt.imshow(image_testing_before_2nd_epoch)
  754. plt.title("Testing Data (2nd Epoch)")
  755. plt.axis("off")
  756.  
  757. plt.subplot(2, 2, 3)
  758. plt.imshow(image_testing_after_50_epochs)
  759. plt.title(f"Testing Data ({epochs} Epochs)")
  760. plt.axis("off")
  761.  
  762. plt.subplot(2, 2, 4)
  763. plt.imshow(image_personNEW)
  764. plt.title(f"New Person\nLabel: {personNEW_label},[{personNEW_prediction}]")
  765. plt.axis("off")
  766.  
  767. # Plot accuracy history
  768. plt.figure(figsize=(12, 5))
  769. plt.plot(range(1, epochs + 1), accuracy_history, marker='o')
  770. plt.title('Accuracy Over Epochs')
  771. plt.xlabel('Epochs')
  772. plt.ylabel('Accuracy')
  773. plt.grid()
  774.  
  775. # Print normalized data
  776. print("Normalized PersonNEW Data:")
  777. print(personNEW_results_normalized)
  778.  
  779. plt.show()
  780.  
  781. print("X_train before normalization:")
  782. print(X_train)
  783. print("X_test before normalization:")
  784. print(X_test)
  785.  
  786. import seaborn as sns
  787.  
  788.  
  789. print("KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK")
  790. print(X_test)
  791. print("HHHHHHHHHHHHHHHHHHHHHHHHHHHHHH")
  792. print(X_train)
  793. print("LLLLLLLLLLLLLLLLLLLLLLLLLLLLL")
  794.  
  795.  
  796. # y_pred_binary = [1 if pred >= 0.5 else 0 for pred in model.predict(X_test_normalized)]
  797.  
  798. # # Create confusion matrix
  799. # conf_matrix = confusion_matrix(y_train, y_pred_binary)
  800. # print(conf_matrix)
  801.  
  802.  
  803. from sklearn.metrics import confusion_matrix
  804. from tensorflow.keras.utils import to_categorical
  805.  
  806. # # Normalize the training data
  807. # min_values = np.min(np.concatenate([X_train, X_test], axis=0), axis=0)
  808. # max_values = np.max(np.concatenate([X_train, X_test], axis=0), axis=0)
  809. # X_train_normalized = (X_train - min_values) / (max_values - min_values)
  810. # X_test_normalized = (X_test - min_values) / (max_values - min_values)
  811.  
  812. np.set_printoptions(threshold=np.inf, precision=4, suppress=True)
  813.  
  814.  
  815. # # Assuming X_test_normalized and y_test are your test set data
  816. # y_pred_binary = [1 if pred >= 0.5 else 0 for pred in model.predict(X_test_normalized)]
  817.  
  818. # # Create confusion matrix using the test set
  819. # conf_matrix = confusion_matrix(y_test, y_pred_binary)
  820. # print(conf_matrix)
  821.  
  822.  
  823.  
  824. # plt.figure(figsize=(6, 6))
  825. # sns.heatmap(conf_matrix, annot=True, fmt="d", cmap="Blues", xticklabels=['Predicted 0', 'Predicted 1'], yticklabels=['Actual 0', 'Actual 1'])
  826. # plt.xlabel("Predicted Label")
  827. # plt.ylabel("True Label")
  828. # plt.title("Confusion Matrix")
  829. # plt.show()
  830.  
  831. # X_train = np.array(X_train)
  832. # y_train_one_hot = np.array(y_train_one_hot)
  833.  
  834. # Rozdělení dat na trénovací a testovací množiny
  835. ###X_train, X_test, y_train, y_test = data[:num_training_rows], data[-num_testing_rows:], labels[:num_training_rows], labels[-num_testing_rows:]
  836.  
  837. ###X_train, X_test, y_train, y_test = data[:num_training_rows], data[:num_training_rows], labels[:num_training_rows], labels[:num_training_rows]
  838. X_train, X_test, y_train, y_test = data[:num_training_rows], data[:num_testing_rows], labels[:num_training_rows], labels[:num_testing_rows]
  839.  
  840. import numpy as np
  841. import matplotlib.pyplot as plt
  842. from sklearn.metrics import confusion_matrix, accuracy_score, precision_score, recall_score, f1_score
  843. import tensorflow as tf
  844. import seaborn as sns
  845.  
  846. # Assuming data splitting and model definition have been done correctly
  847.  
  848. # Compile the model
  849. model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
  850.  
  851. # Train the model
  852. print("Training Start")
  853. for epoch in tqdm_notebook(range(1000), desc="Training Progress"):
  854.     model.fit(np.array(X_train_normalized), np.array(y_train), epochs=1, verbose=0)
  855. print("Training Complete")
  856.  
  857. # Generate predictions from the model
  858. predictions = (model.predict(X_test_normalized) > 0.5).astype(int)
  859.  
  860. # Convert y_test to a numpy array and then to binary labels
  861. y_test_array = np.array(y_test)  # Convert y_test to a numpy array
  862. y_test_binary = (y_test_array > 0.5).astype(int)  # Convert to binary
  863.  
  864. # Compute the confusion matrix
  865. conf_matrix = confusion_matrix(y_test_binary, predictions)
  866.  
  867. # Evaluate the model's performance
  868. accuracy = accuracy_score(y_test_binary, predictions)
  869. precision = precision_score(y_test_binary, predictions)
  870. recall = recall_score(y_test_binary, predictions)
  871. f1 = f1_score(y_test_binary, predictions)
  872.  
  873. # Display the confusion matrix
  874. sns.heatmap(conf_matrix, annot=True, fmt='d', cmap='Blues')
  875. plt.xlabel('Predicted')
  876. plt.ylabel('Actual')
  877. plt.title('Confusion Matrix')
  878. plt.show()
  879.  
  880. print(f"Accuracy: {accuracy:.4f}")
  881. print(f"Precision: {precision:.4f}")
  882. print(f"Recall: {recall:.4f}")
  883. print(f"F1 Score: {f1:.4f}")
  884.  
  885. print(f"Confusion Matrix2122:\n{conf_matrix}")
  886.  
  887.  
  888. import random
  889.  
  890. def find_best_pair(min_val, max_val, num_features, model, min_values, max_values):
  891.     best_pair = None
  892.     best_prediction = 1
  893.     for _ in range(1000):  # Number of iterations to find the best pair
  894.         new_data = np.random.uniform(min_val, max_val, num_features)
  895.         new_data_normalized = (new_data - min_values) / (max_values - min_values)
  896.        
  897.         # Suppress model output
  898.         tf.get_logger().setLevel('ERROR')
  899.         with tf.device('/CPU:0'):  # Ensure to run on CPU to minimize unwanted logs
  900.             prediction = model.predict(np.array([new_data_normalized]), verbose=0)[0][0]
  901.         tf.get_logger().setLevel('INFO')
  902.        
  903.         if prediction < best_prediction:
  904.             best_prediction = prediction
  905.             best_pair = new_data
  906.     return best_pair, best_prediction
  907.  
  908.  
  909.  
  910. best_pair, best_prediction = find_best_pair(min_values, max_values, len(X_train[0]), model, min_values, max_values)
  911.  
  912.  
  913. def find_worst_pair(min_val, max_val, num_features, model, min_values, max_values):
  914.     worst_pair = None
  915.     worst_prediction = 0
  916.     for _ in range(1000):  # Number of iterations to find the best pair
  917.         new_data = np.random.uniform(min_val, max_val, num_features)
  918.         new_data_normalized = (new_data - min_values) / (max_values - min_values)
  919.        
  920.         # Suppress model output
  921.         tf.get_logger().setLevel('ERROR')
  922.         with tf.device('/CPU:0'):  # Ensure to run on CPU to minimize unwanted logs
  923.             prediction = model.predict(np.array([new_data_normalized]), verbose=0)[0][0]
  924.         tf.get_logger().setLevel('INFO')
  925.        
  926.         if prediction > worst_prediction:
  927.             worst_prediction = prediction
  928.             worst_pair = new_data
  929.     return worst_pair, worst_prediction
  930.  
  931.  
  932.  
  933. worst_pair, worst_prediction = find_worst_pair(min_values, max_values, len(X_train[0]), model, min_values, max_values)
  934.  
  935.  
  936. print(f"Best Pair: {best_pair}, Best Prediction: {best_prediction}")
  937. print(f"Worst Pair: {worst_pair}, Worst Prediction: {worst_prediction}")
  938.  
  939. import numpy as np
  940. import matplotlib.pyplot as plt
  941. from sklearn.decomposition import PCA
  942. import tensorflow as tf
  943. from tqdm.notebook import tqdm_notebook
  944.  
  945. # Vaše data
  946. # A = [
  947. #     [23.657800719276743,18.859916797201468,0,0],
  948. #     [22.573729142097473,17.96922325097786,0,0],
  949. #     [32.55342396968757,29.463651408558803,0,0],
  950. #     [6.718035041529263,25.704665468161718,2,1],
  951. #     [14.401918566243225,16.770856492924658,0,0],
  952. #     [17.457907312962234,21.76521470574044,0,0],
  953. #     [20.02796946568093,73.45445954770891,2,1],
  954. #     [30.295138369778076,62.901112886193246,2,1],
  955. #     [15.128977804449633,32.40267702110393,0,0],
  956. #     [30.179457395820013,58.982492125646104,2,1],
  957. #     [28.01649701854089,63.92781357637711,2,1],
  958. #     [16.791838457871147,42.33482314089884,0,0],
  959. #     [10.583694293380976,19.61926728942497,0,0],
  960. #     [26.634447074406467,91.96624817360987,2,1],
  961. #     [26.217868623367643,36.400293587062976,0,0],
  962. #     [17.689396788624936,60.79797114006423,2,1],
  963. #     [33.17193822527976,66.75277364959176,2,1],
  964. #     [23.793952755709153,22.57501437360518,0,0],
  965. #     [37.844484133572124,36.320623921263156,2,1],
  966. #     [35.16135413357336,33.16395078484642,2,1],
  967. #     [29.380894071974286,25.28297332192533,0,0],
  968. #     [31.65893504663792,73.13603413708854,2,1],
  969. # ]
  970.  
  971. # # Převod na NumPy pole
  972. # A = np.array(A)
  973.  
  974. # Extrakce dat a labelů
  975. X = A[:, :-1]  # Všechny sloupce kromě posledního jsou vstupy
  976. y = A[:, -1]  # Poslední sloupec je label
  977.  
  978. # Normalizace dat
  979. min_values = np.min(X, axis=0)
  980. max_values = np.max(X, axis=0)
  981. X_normalized = (X - min_values) / (max_values - min_values)
  982.  
  983. # Rozdělení dat na trénovací a testovací množiny
  984. num_training_rows = 15
  985. X_train_normalized = X_normalized[:num_training_rows]
  986. y_train = y[:num_training_rows]
  987. X_test_normalized = X_normalized[num_training_rows:]
  988. y_test = y[num_training_rows:]
  989.  
  990. # Definice a kompilace modelu
  991. model = tf.keras.Sequential([
  992.     tf.keras.layers.Dense(256, activation='relu', input_shape=(len(X_train_normalized[0]),)),
  993.     tf.keras.layers.Dropout(0.3),
  994.     tf.keras.layers.Dense(128, activation='relu'),
  995.     tf.keras.layers.Dropout(0.3),
  996.     tf.keras.layers.Dense(64, activation='relu'),
  997.     tf.keras.layers.Dropout(0.3),
  998.     tf.keras.layers.Dense(1, activation='sigmoid')
  999. ])
  1000.  
  1001. model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
  1002.  
  1003. # Trénování modelu
  1004. epochs = 138
  1005. accuracy_history = []
  1006.  
  1007. for epoch in tqdm_notebook(range(epochs)):
  1008.     history = model.fit(X_train_normalized, np.array(y_train), epochs=1, verbose=0, shuffle=True)
  1009.     accuracy_history.append(history.history['accuracy'][0])
  1010.  
  1011. # Aplikace PCA
  1012. pca = PCA(n_components=2)  # Snížení na 2 komponenty
  1013. X_pca = pca.fit_transform(X_normalized)
  1014.  
  1015. # Vizualizace výsledků
  1016. plt.figure()
  1017. plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y)
  1018. plt.xlabel('První hlavní komponenta')
  1019. plt.ylabel('Druhá hlavní komponenta')
  1020. plt.title('PCA na vašich datech')
  1021. plt.show()
  1022.  
  1023. ##################### LDA
  1024.  
  1025. X = A[:, :-1]  # Všechny sloupce kromě posledního jsou vstupy
  1026. y = A[:, -1]  # Poslední sloupec je label
  1027.  
  1028. # Normalizace dat
  1029. min_values = np.min(X, axis=0)
  1030. max_values = np.max(X, axis=0)
  1031. X_normalized = (X - min_values) / (max_values - min_values)
  1032.  
  1033. # Rozdělení dat na trénovací a testovací množiny
  1034. num_training_rows = A.shape[0]
  1035.  
  1036. X_train_normalized = X_normalized[:num_training_rows]
  1037. y_train = y[:num_training_rows]
  1038. X_test_normalized = X_normalized[num_training_rows:]
  1039. y_test = y[num_training_rows:]
  1040.  
  1041. # # Definice a kompilace modelu
  1042. # model = tf.keras.Sequential([
  1043. #     tf.keras.layers.Dense(256, activation='relu', input_shape=(len(X_train_normalized[0]),)),
  1044. #     tf.keras.layers.Dropout(0.3),
  1045. #     tf.keras.layers.Dense(128, activation='relu'),
  1046. #     tf.keras.layers.Dropout(0.3),
  1047. #     tf.keras.layers.Dense(64, activation='relu'),
  1048. #     tf.keras.layers.Dropout(0.3),
  1049. #     tf.keras.layers.Dense(1, activation='sigmoid')
  1050. # ])
  1051.  
  1052. #model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
  1053.  
  1054. from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA
  1055.  
  1056. # Trénování modelu
  1057. epochs = 138
  1058. accuracy_history = []
  1059.  
  1060. for epoch in tqdm_notebook(range(epochs)):
  1061.     history = model.fit(X_train_normalized, np.array(y_train), epochs=1, verbose=0, shuffle=True)
  1062.     accuracy_history.append(history.history['accuracy'][0])
  1063.  
  1064. # Aplikace LDA
  1065. lda = LDA(n_components=1)  # Snížení na 2 komponenty
  1066. X_lda = lda.fit_transform(X_normalized, y)
  1067.  
  1068. # # Vizualizace výsledků
  1069. # plt.figure()
  1070. # plt.scatter(X_lda[:, 0], X_lda[:, 1], c=y)
  1071. # plt.xlabel('První diskriminační komponenta')
  1072. # plt.ylabel('Druhá diskriminační komponenta')
  1073. # plt.title('LDA na vašich datech')
  1074. # plt.show()
  1075.  
  1076. lda = LDA(n_components=1)
  1077. X_lda = lda.fit_transform(X_train_normalized, y_train)
  1078.  
  1079.  
  1080. # Vizualizace výsledků LDA
  1081. plt.figure()
  1082. plt.scatter(X_lda[:, 0], np.zeros_like(X_lda), c=y_train)
  1083. plt.xlabel('První diskriminační komponenta')
  1084. plt.title('LDA s učitelem')
  1085. plt.show()
  1086.  
  1087. ###################################################################################################################
  1088.  
  1089.  
  1090. import numpy as np
  1091. import matplotlib.pyplot as plt
  1092. import tensorflow as tf
  1093. from sklearn.metrics import recall_score, confusion_matrix, accuracy_score, precision_score, f1_score
  1094. import seaborn as sns
  1095.  
  1096. # # Vaše data
  1097. # A = [
  1098. #     [23.657800719276743, 18.859916797201468, 0, 0],
  1099. #     [22.573729142097473, 17.96922325097786, 0, 0],
  1100. #     [32.55342396968757, 29.463651408558803, 0, 0],
  1101. #     [6.718035041529263, 25.704665468161718, 2, 1],
  1102. #     [14.401918566243225, 16.770856492924658, 0, 0],
  1103. #     [17.457907312962234, 21.76521470574044, 0, 0],
  1104. #     [20.02796946568093, 73.45445954770891, 2, 1],
  1105. #     [30.295138369778076, 62.901112886193246, 2, 1],
  1106. #     [15.128977804449633, 32.40267702110393, 0, 0],
  1107. #     [30.179457395820013, 58.982492125646104, 2, 1],
  1108. #     [28.01649701854089, 63.92781357637711, 2, 1],
  1109. #     [16.791838457871147, 42.33482314089884, 0, 0],
  1110. #     [10.583694293380976, 19.61926728942497, 0, 0],
  1111. #     [26.634447074406467, 91.96624817360987, 2, 1],
  1112. #     [26.217868623367643, 36.400293587062976, 0, 0],
  1113. #     [17.689396788624936, 60.79797114006423, 2, 1],
  1114. #     [33.17193822527976, 66.75277364959176, 2, 1],
  1115. #     [23.793952755709153, 22.57501437360518, 0, 0],
  1116. #     [37.844484133572124, 36.320623921263156, 2, 1],
  1117. #     [35.16135413357336, 33.16395078484642, 2, 1],
  1118. #     [29.380894071974286, 25.28297332192533, 0, 0],
  1119. #     [31.65893504663792, 73.13603413708854, 2, 1],
  1120. # ]
  1121.  
  1122. # # Převod na NumPy pole
  1123. # A = np.array(A)
  1124.  
  1125. # Rozdělení na vstupní data (X) a cílové proměnné (y)
  1126. X = A[:, :-1]
  1127. y = A[:, -1]
  1128.  
  1129. # Rozdělení na trénovací a testovací sadu (v tomto příkladě použijeme celou sadu jako trénovací pro jednoduchost)
  1130. X_train, y_train = X, y
  1131. X_test, y_test = X, y
  1132.  
  1133. # Normalizace dat
  1134. min_values = np.min(X_train, axis=0)
  1135. max_values = np.max(X_train, axis=0)
  1136. X_train_normalized = (X_train - min_values) / (max_values - min_values)
  1137. X_test_normalized = (X_test - min_values) / (max_values - min_values)
  1138.  
  1139. # Definice modelu
  1140. model = tf.keras.Sequential([
  1141.     tf.keras.layers.Dense(256, activation='relu', input_shape=(X_train_normalized.shape[1],)),
  1142.     tf.keras.layers.Dropout(0.3),
  1143.     tf.keras.layers.Dense(128, activation='relu'),
  1144.     tf.keras.layers.Dropout(0.3),
  1145.     tf.keras.layers.Dense(64, activation='relu'),
  1146.     tf.keras.layers.Dropout(0.3),
  1147.     tf.keras.layers.Dense(1, activation='sigmoid')
  1148. ])
  1149.  
  1150. # Použití Adam optimizer s learning rate schedulerem
  1151. lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(
  1152.     initial_learning_rate=1e-3,
  1153.     decay_steps=10000,
  1154.     decay_rate=0.9
  1155. )
  1156. optimizer = tf.keras.optimizers.Adam(learning_rate=lr_schedule)
  1157.  
  1158. # Kompilace modelu
  1159. model.compile(optimizer=optimizer, loss='binary_crossentropy', metrics=['accuracy', tf.keras.metrics.Recall()])
  1160.  
  1161. # Trénování modelu
  1162. history = model.fit(X_train_normalized, y_train, epochs=50, verbose=0, shuffle=True)
  1163.  
  1164. # Predikce
  1165. y_pred_prob = model.predict(X_test_normalized)
  1166. y_pred = (y_pred_prob > 0.5).astype(int)
  1167.  
  1168. # Výpočet metrik
  1169. recall = recall_score(y_test, y_pred)
  1170. conf_matrix = confusion_matrix(y_test, y_pred)
  1171.  
  1172. # Vyhodnocení výkonu modelu
  1173. accuracy = accuracy_score(y_test, y_pred)
  1174. precision = precision_score(y_test, y_pred)
  1175. f1 = f1_score(y_test, y_pred)
  1176.  
  1177. # Výpis metrik
  1178. print(f"Recall: {recall:.4f}")
  1179. print(f"Accuracy: {accuracy:.4f}")
  1180. print(f"Precision: {precision:.4f}")
  1181. print(f"F1 Score: {f1:.4f}")
  1182. print(f"Confusion Matrix:\n{conf_matrix}")
  1183.  
  1184. # Zobrazení confusion matrix
  1185. sns.heatmap(conf_matrix, annot=True, fmt='d', cmap='Blues')
  1186. plt.xlabel('Predicted')
  1187. plt.ylabel('Actual')
  1188. plt.title('Confusion Matrix')
  1189. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement