Advertisement
max2201111

BLACK OK very GOOD VK with shuffle WORST BEST PREDICTION PAIR

May 26th, 2024
615
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 15.57 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. from IPython.display import display
  51. from IPython.display import Javascript
  52. display(Javascript('IPython.OutputArea.auto_scroll_threshold = 9999;'))
  53.  
  54. label_colors = {0: [0, 128, 0], 1: [255, 0, 0]}
  55. label_colors_testing = {0: [0, 128, 0], 1: [255, 0, 0]}
  56.  
  57. %matplotlib inline
  58.  
  59. # Function to create images based on predictions
  60. def create_image(data, predictions):
  61.     num_rows, num_columns = len(data), len(data[0])
  62.     image = np.zeros((num_rows, num_columns + 1, 3), dtype=np.uint8)
  63.  
  64.     for i in range(num_rows):
  65.         for j in range(num_columns):
  66.             pixel_value = int(np.interp(data[i][j], [np.min(data), np.max(data)], [0, 255]))
  67.             image[i, j] = np.array([pixel_value] * 3)
  68.  
  69.         # Use the specified color for the last column based on the label
  70.         image[i, -1] = label_colors[predictions[i]]
  71.  
  72.     return image
  73.  
  74. def create_imageN(data, predictions, label_colors=None):
  75.     num_rows, num_columns = len(data), len(data[0])
  76.     image = np.zeros((num_rows, num_columns + 1, 3), dtype=np.uint8)
  77.  
  78.     data_array = np.array(data)  # Convert data to a NumPy array
  79.  
  80.     for i in range(num_rows):
  81.         for j in range(num_columns - 1):  # Exclude the last column for now
  82.             # Map data values to the full range of 0 to 255
  83.             pixel_value = int(np.interp(data_array[i, j], [np.min(data_array[:, j]), np.max(data_array[:, j])], [0, 255]))
  84.             image[i, j] = np.array([pixel_value] * 3)
  85.  
  86.         # Use the specified color for the last column based on the label
  87.         if label_colors is not None:
  88.             image[i, -1] = label_colors[predictions[i]]
  89.         else:
  90.             # If label_colors is not provided, set the last column to grayscale
  91.             pixel_value = int(np.interp(predictions[i], [0, 1], [0, 255]))
  92.             image[i, -1] = np.array([pixel_value] * 3)
  93.  
  94.     return image
  95.  
  96. # Load data from a file
  97. from google.colab import files
  98. uploaded = files.upload()
  99.  
  100. # Tento kód otevře dialogové okno pro výběr souboru z vašeho počítače.
  101. import io
  102. import pandas as pd
  103.  
  104. # Předpokládáme, že jste nahráli CSV soubor
  105. for fn in uploaded.keys():
  106.     print('User uploaded file "{name}" with length {length} bytes'.format(name=fn, length=len(uploaded[fn])))
  107.     path = io.BytesIO(uploaded[fn])  # Pro soubory, které potřebují být čteny jako binární objekty
  108.     df = pd.read_csv(path)
  109.     print(df.head())  # Vypíše prvních pět řádků DataFrame
  110.  
  111. all_results = []
  112. import os
  113. import shutil
  114. import ast
  115.  
  116. for filename in uploaded.keys():
  117.     original_path = f"/content/{filename}"
  118.     destination_path = os.path.join("/content/", "/content/DATA2")
  119.     shutil.move(original_path, destination_path)
  120.     print(f"Soubor {filename} byl přesunut do {destination_path}")
  121.  
  122. file_path = '/content/DATA2'  # Cesta k souboru
  123. with open(file_path, 'r') as file:
  124.     code = file.read()
  125.  
  126. A_list = ast.literal_eval(code)
  127.  
  128. # Převod na NumPy pole
  129. A = np.array(A_list)
  130.  
  131. # Assign values to variables dynamically based on the rows of matrix A
  132. for i, row in enumerate(A, start=1):
  133.     globals()[f"person{i}_results"] = list(row)
  134.  
  135. # Print the assigned variables
  136. for i in range(1, len(A) + 1):
  137.     all_results.append(f"person{i}_results")
  138.  
  139. result_variables = []
  140.  
  141. # Loop through the variable names and get the corresponding variables using globals()
  142. for var_name in all_results:
  143.     result_variables.append(globals()[var_name])
  144.  
  145. # Now, result_variables contains the variables with names specified in variable_names
  146. all_results = result_variables
  147. new_persons_results = result_variables
  148.  
  149. # Extract the last column (0 nebo 1) as labels
  150. labels = [results[-1] for results in all_results]
  151.  
  152. # Remove the last column from the dataset
  153. data = [results[:-1] for results in all_results]
  154.  
  155. # Define the number of rows for training and testing
  156. num_training_rows = 100
  157. num_testing_rows = 100
  158.  
  159. # Split the data into training and testing datasets
  160. X_train, X_test, y_train, y_test = data[:num_training_rows], data[:num_testing_rows], labels[:num_training_rows], labels[:num_testing_rows]
  161.  
  162. # Normalize the training data
  163. min_values = np.min(X_train, axis=0)
  164. max_values = np.max(X_train, axis=0)
  165. X_train_normalized = (X_train - min_values) / (max_values - min_values)
  166.  
  167. # Normalize the testing data using the min and max values of the training data
  168. X_test_normalized = (X_test - min_values) / (max_values - min_values)
  169.  
  170. # Print normalized training data
  171. print("Normalized Training Data:")
  172. print(X_train_normalized)
  173. print("Adenormalized", X_train_normalized * (max_values - min_values) + min_values, "Bdenormalized")
  174.  
  175. # Define a simple neural network model
  176. model = tf.keras.Sequential([
  177.     tf.keras.layers.Dense(128, activation='relu', input_shape=(len(X_train[0]),)),
  178.     tf.keras.layers.Dense(64, activation='relu'),
  179.     tf.keras.layers.Dense(1, activation='sigmoid')
  180. ])
  181.  
  182. # Compile the model
  183. model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
  184.  
  185. # Lists to store accuracy values
  186. accuracy_history = []
  187.  
  188. # Create images for the training data
  189. image_training = np.zeros((num_training_rows, len(X_train[0]) + 1, 3), dtype=np.uint8)
  190.  
  191. min_pixel_value = np.min(X_train_normalized)
  192. max_pixel_value = np.max(X_train_normalized)
  193.  
  194. # Populate image_training with consistent gray and red/green colors based on the labels in the last column
  195. for i, label in enumerate(y_train):
  196.     for j in range(len(X_train[0])):
  197.         pixel_value = int(np.interp(X_train_normalized[i][j], [min_pixel_value, max_pixel_value], [0, 255]))
  198.         image_training[i, j] = np.array([pixel_value] * 3)
  199.     image_training[i, -1] = np.array([128, 128, 128])
  200.     if label == 0:
  201.         image_training[i, -1] = np.array([0, 128, 0])
  202.     elif label == 1:
  203.         image_training[i, -1] = np.array([255, 0, 0])
  204.  
  205. ### ZDE VLOZTE DATA OD NOVYCH PACIENTU
  206.  
  207. # Train the model for 400 epochs
  208. epochs = 138
  209.  
  210. import sys
  211.  
  212. # Function to find the best pair of values
  213. def find_best_pair(min_val, max_val, num_features, model, min_values, max_values):
  214.     best_pair = None
  215.     best_prediction = 0
  216.     for _ in range(1000):  # Number of iterations to find the best pair
  217.         new_data = np.random.uniform(min_val, max_val, num_features)
  218.         new_data_normalized = (new_data - min_values) / (max_values - min_values)
  219.        
  220.         # Potlačení výstupů modelu
  221.         tf.get_logger().setLevel('ERROR')
  222.         with tf.device('/CPU:0'):  # Ensure to run on CPU to minimize unwanted logs
  223.             prediction = model.predict(np.array([new_data_normalized]), verbose=0)[0][0]
  224.         tf.get_logger().setLevel('INFO')
  225.        
  226.         if prediction > best_prediction:
  227.             best_prediction = prediction
  228.             best_pair = new_data
  229.     return best_pair, best_prediction
  230.  
  231. def find_worst_pair(min_val, max_val, num_features, model, min_values, max_values):
  232.     worst_pair = None
  233.     worst_prediction = 1
  234.     for _ in range(1000):  # Number of iterations to find the best pair
  235.         new_data = np.random.uniform(min_val, max_val, num_features)
  236.         new_data_normalized = (new_data - min_values) / (max_values - min_values)
  237.        
  238.         # Potlačení výstupů modelu
  239.         tf.get_logger().setLevel('ERROR')
  240.         with tf.device('/CPU:0'):  # Ensure to run on CPU to minimize unwanted logs
  241.             prediction = model.predict(np.array([new_data_normalized]), verbose=0)[0][0]
  242.         tf.get_logger().setLevel('INFO')
  243.        
  244.         if prediction < worst_prediction:
  245.             worst_prediction = prediction
  246.             worst_pair = new_data
  247.     return worst_pair, worst_prediction
  248.  
  249. # Potlačení nadbytečných výstupů modelu
  250. tf.get_logger().setLevel('ERROR')
  251. tf.autograph.set_verbosity(0)
  252.  
  253. for epoch in tqdm(range(epochs)):
  254.     history = model.fit(X_train_normalized, np.array(y_train), epochs=1, verbose=0, shuffle=True)
  255.     accuracy_history.append(history.history['accuracy'][0])
  256.  
  257.     if epoch == 1:
  258.         # Normalize the testing data
  259.         X_test_normalized = (X_test - min_values) / (max_values - min_values)
  260.         y_pred_after_2nd_epoch = model.predict(X_test_normalized, verbose=0)
  261.         y_pred_binary_after_2nd_epoch = [1 if pred >= 0.5 else 0 for pred in y_pred_after_2nd_epoch]
  262.         image_testing_before_2nd_epoch = create_image(X_test_normalized, y_pred_binary_after_2nd_epoch)
  263.  
  264.     if epoch >= epochs-1:
  265.         print(f"HERE HERE Epoch: {epoch}, Epochs: {epochs}\n")
  266.         sys.stdout.flush()
  267.  
  268.         # Iterate through new persons
  269.         for idx, personNEW_results in enumerate(new_persons_results, start=1):
  270.             # Ensure that personNEW_results has the same number of features as the model expects
  271.             if len(personNEW_results) != len(X_train[0]):
  272.                 # Potlač chybové zprávy o nevyhovujícím počtu funkcí
  273.                 continue
  274.  
  275.             personNEW_results_normalized = (np.array(personNEW_results) - min_values) / (max_values - min_values)
  276.  
  277.             personNEW_prediction = model.predict(np.array([personNEW_results_normalized]), verbose=0)[0][0]
  278.             personNEW_label = 1 if personNEW_prediction >= 0.5 else 0
  279.             y_pred_after_50_epochs = model.predict(X_test_normalized, verbose=0)
  280.             y_pred_binary_after_50_epochs = [1 if pred >= 0.5 else 0 for pred in y_pred_after_50_epochs]
  281.             image_testing_after_50_epochs = create_image(X_test_normalized, y_pred_binary_after_50_epochs)
  282.  
  283.             # Create an image for the new person
  284.             image_personNEW = create_imageN([personNEW_results_normalized], [personNEW_label], label_colors)
  285.  
  286.             # Display the images
  287.             plt.figure(figsize=(5, 5))
  288.             plt.imshow(image_personNEW)
  289.             plt.title(f"New Person {idx}\nLabel: {personNEW_label}, Prediction: {personNEW_prediction}")
  290.             plt.axis("off")
  291.             plt.show()
  292.  
  293. # Find the best pair of values to add to new_persons_results
  294. best_pair, best_prediction = find_best_pair(min_values, max_values, len(X_train[0]), model, min_values, max_values)
  295. new_persons_results.append(best_pair)
  296.  
  297. worst_pair, worst_prediction = find_worst_pair(min_values, max_values, len(X_train[0]), model, min_values, max_values)
  298. new_persons_results.append(worst_pair)
  299.  
  300.  
  301. print(f"Best Pair: {best_pair}, Best Prediction: {best_prediction}")
  302.  
  303. print(f"Worst Pair: {worst_pair}, Worst Prediction: {worst_prediction}")
  304.  
  305. # Display the images
  306. plt.figure(figsize=(25, 15))
  307. plt.subplot(2, 2, 1)
  308. plt.imshow(image_training)
  309. plt.title("Training Data")
  310. plt.axis("off")
  311.  
  312. plt.subplot(2, 2, 2)
  313. plt.imshow(image_testing_before_2nd_epoch)
  314. plt.title("Testing Data (2nd Epoch)")
  315. plt.axis("off")
  316.  
  317. plt.subplot(2, 2, 3)
  318. plt.imshow(image_testing_after_50_epochs)
  319. plt.title(f"Testing Data ({epochs} Epochs)")
  320. plt.axis("off")
  321.  
  322. plt.subplot(2, 2, 4)
  323. plt.imshow(image_personNEW)
  324. plt.title(f"New Person\nLabel: {personNEW_label},[{personNEW_prediction}]")
  325. plt.axis("off")
  326.  
  327. # Plot accuracy history
  328. plt.figure(figsize=(12, 5))
  329. plt.plot(range(1, epochs + 1), accuracy_history, marker='o')
  330. plt.title('Accuracy Over Epochs')
  331. plt.xlabel('Epochs')
  332. plt.ylabel('Accuracy')
  333. plt.grid()
  334.  
  335. # Print normalized data
  336. print("Normalized PersonNEW Data:")
  337. print(personNEW_results_normalized)
  338.  
  339. plt.show()
  340.  
  341. print("X_train before normalization:")
  342. print(X_train)
  343. print("X_test before normalization:")
  344. print(X_test)
  345.  
  346. import seaborn as sns
  347.  
  348. print("KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK")
  349. print(X_test)
  350. print("HHHHHHHHHHHHHHHHHHHHHHHHHHHHHH")
  351. print(X_train)
  352. print("LLLLLLLLLLLLLLLLLLLLLLLLLLLLL")
  353.  
  354. from sklearn.metrics import confusion_matrix
  355. from tensorflow.keras.utils import to_categorical
  356.  
  357. np.set_printoptions(threshold=np.inf, precision=4, suppress=True)
  358.  
  359. # Generate predictions from the model
  360. predictions = (model.predict(X_test_normalized, verbose=0) > 0.5).astype(int)
  361.  
  362. # Convert y_test to a numpy array and then to binary labels
  363. y_test_array = np.array(y_test)  # Convert y_test to a numpy array
  364. y_test_binary = (y_test_array > 0.5).astype(int)  # Convert to binary
  365.  
  366. # Compute the confusion matrix
  367. conf_matrix = confusion_matrix(y_test_binary, predictions)
  368.  
  369. # Evaluate the model's performance
  370. accuracy = accuracy_score(y_test_binary, predictions)
  371. precision = precision_score(y_test_binary, predictions)
  372. recall = recall_score(y_test_binary, predictions)
  373. f1 = f1_score(y_test_binary, predictions)
  374.  
  375. # Display the confusion matrix
  376. sns.heatmap(conf_matrix, annot=True, fmt='d', cmap='Blues')
  377. plt.xlabel('Predicted')
  378. plt.ylabel('Actual')
  379. plt.title('Confusion Matrix')
  380. plt.show()
  381.  
  382. print(f"Accuracy: {accuracy:.4f}")
  383. print(f"Precision: {precision:.4f}")
  384. print(f"Recall: {recall:.4f}")
  385. print(f"F1 Score: {f1:.4f}")
  386.  
  387. print(f"Confusion Matrix:\n{conf_matrix}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement