Advertisement
max2201111

create_imageN jen jednou GOOD VK

May 25th, 2024
526
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 13.16 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. %matplotlib inline
  60.  
  61. def create_imageN(data, predictions, label_colors=None):
  62.     # Convert data to a NumPy array
  63.     data = np.array(data)
  64.  
  65.     num_rows, num_columns = data.shape
  66.     image = np.zeros((num_rows, num_columns + 1, 3), dtype=np.uint8)
  67.  
  68.     # Normalize the first two columns independently
  69.     for j in range(2):
  70.         min_pixel_value = np.min(data[:, j])
  71.         max_pixel_value = np.max(data[:, j])
  72.         for i in range(num_rows):
  73.             pixel_value = int(np.interp(data[i][j], [min_pixel_value, max_pixel_value], [0, 255]))
  74.             image[i, j] = np.array([pixel_value] * 3)
  75.  
  76.     # Normalize the last column separately to achieve grayscale
  77.     min_pixel_value_last = np.min(data[:, -1])
  78.     max_pixel_value_last = np.max(data[:, -1])
  79.     for i in range(num_rows):
  80.         pixel_value_last = int(np.interp(data[i][-1], [min_pixel_value_last, max_pixel_value_last], [0, 255]))
  81.         image[i, -1] = np.array([pixel_value_last] * 3)
  82.  
  83.         # Use the specified color for the last column based on the label
  84.         if label_colors is not None:
  85.             image[i, -1] = label_colors[predictions[i]]
  86.  
  87.     return image
  88.  
  89. # Load data from a file
  90. #file_path = 'C:/Users/Hynek/Desktop/example4.txt'
  91. from google.colab import files
  92. uploaded = files.upload()
  93.  
  94. # Tento kód otevře dialogové okno pro výběr souboru z vašeho počítače.
  95. import io
  96. import pandas as pd
  97.  
  98. # Předpokládáme, že jste nahráli CSV soubor
  99. for fn in uploaded.keys():
  100.     print('User uploaded file "{name}" with length {length} bytes'.format(
  101.         name=fn, length=len(uploaded[fn])))
  102.     path = io.BytesIO(uploaded[fn])  # Pro soubory, které potřebují být čteny jako binární objekty
  103.     df = pd.read_csv(path)
  104.     print(df.head())  # Vypíše prvních pět řádků DataFrame
  105.  
  106. all_results = []
  107. import os
  108. import shutil
  109. import ast
  110.  
  111. for filename in uploaded.keys():
  112.     original_path = f"/content/{filename}"
  113.     destination_path = os.path.join("/content/", "/content/DATA2")
  114.     shutil.move(original_path, destination_path)
  115.     print(f"Soubor {filename} byl přesunut do {destination_path}")
  116.  
  117. file_path = '/content/DATA2'  # Cesta k souboru
  118. with open(file_path, 'r') as file:
  119.     code = file.read()
  120.  
  121. A_list = ast.literal_eval(code)
  122.  
  123. # Převod na NumPy pole
  124. A = np.array(A_list)
  125.  
  126. # Assign values to variables dynamically based on the rows of matrix A
  127. for i, row in enumerate(A, start=1):
  128.     globals()[f"person{i}_results"] = list(row)
  129.  
  130. # Print the assigned variables
  131. for i in range(1, len(A) + 1):
  132.     all_results.append(f"person{i}_results")
  133.  
  134. result_variables = []
  135.  
  136. # Loop through the variable names and get the corresponding variables using globals()
  137. for var_name in all_results:
  138.     result_variables.append(globals()[var_name])
  139.  
  140. # Now, result_variables contains the variables with names specified in variable_names
  141. all_results = result_variables
  142. new_persons_results = result_variables
  143.  
  144. # Extract the last column (0 or 1) as labels
  145. labels = [results[-1] for results in all_results]
  146.  
  147. # Remove the last column from the dataset
  148. data = [results[:-1] for results in all_results]
  149.  
  150. # Rozdělení dat na trénovací a testovací sady s náhodným mícháním
  151. from sklearn.model_selection import train_test_split
  152. X_train, X_test, y_train, y_test = train_test_split(data, labels, test_size=0.2, random_state=42, shuffle=True)
  153.  
  154. # Normalize the training data
  155. min_values = np.min(X_train, axis=0)
  156. max_values = np.max(X_train, axis=0)
  157. X_train_normalized = (X_train - min_values) / (max_values - min_values)
  158.  
  159. # Normalize the testing data using the min and max values of the training data
  160. X_test_normalized = (X_test - min_values) / (max_values - min_values)
  161.  
  162. # Print normalized training data
  163. print("Normalized Training Data:")
  164. print(X_train_normalized)
  165. print("Adenormalized",X_train_normalized*(max_values - min_values)+min_values,"Bdenormalized")
  166.  
  167. # Define a simple neural network model
  168. model = tf.keras.Sequential([
  169.     tf.keras.layers.Dense(128, activation='relu', input_shape=(len(X_train[0]),)),
  170.     tf.keras.layers.Dense(64, activation='relu'),
  171.     tf.keras.layers.Dense(1, activation='sigmoid')
  172. ])
  173.  
  174. # Compile the model
  175. model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
  176.  
  177. # Lists to store accuracy values
  178. accuracy_history = []
  179.  
  180. # Create images for the training data
  181. image_training = np.zeros((len(X_train), len(X_train[0]) + 1, 3), dtype=np.uint8)
  182.  
  183. min_pixel_value = np.min(X_train_normalized)
  184. max_pixel_value = np.max(X_train_normalized)
  185.  
  186. # Populate image_training with consistent gray and red/green colors based on the labels in the last column
  187. for i, label in enumerate(y_train):
  188.     for j in range(len(X_train[0])):
  189.         pixel_value = int(np.interp(X_train_normalized[i][j], [min_pixel_value, max_pixel_value], [0, 255]))
  190.         image_training[i, j] = np.array([pixel_value] * 3)
  191.     image_training[i, -1] = np.array([128, 128, 128])
  192.     if label == 0:
  193.         image_training[i, -1] = np.array([0, 128, 0])
  194.     elif label == 1:
  195.         image_training[i, -1] = np.array([255, 0, 0])
  196.  
  197. from tqdm.notebook import tqdm_notebook
  198.  
  199. ###ZDE VLOZTE DATA OD NOVYCH PACIENTU
  200.  
  201. # Train the model for 400 epochs
  202. epochs = 1397
  203. # Assuming 'new_persons_results' is a list of new persons, where each person is represented as a list of features
  204. new_persons_results = [
  205.     [23.65780072, 18.8599168 ],
  206.     [22.57372914, 17.96922325],
  207.     [32.55342397, 29.46365141],
  208.     [ 6.71803504, 25.70466547],
  209.     [14.40191857, 16.77085649],
  210.     [17.45790731, 21.76521471],
  211.     [20.02796947, 73.45445955],
  212. ]
  213.  
  214. import sys
  215.  
  216. for epoch in tqdm_notebook(range(epochs)):
  217.     history = model.fit(X_train_normalized, np.array(y_train), epochs=1, verbose=0, shuffle=True)
  218.     accuracy_history.append(history.history['accuracy'][0])
  219.  
  220.     if epoch == 1:
  221.         # Normalize the testing data
  222.         X_test_normalized = (X_test - min_values) / (max_values - min_values)
  223.         y_pred_after_2nd_epoch = model.predict(X_test_normalized)
  224.         y_pred_binary_after_2nd_epoch = [1 if pred >= 0.5 else 0 for pred in y_pred_after_2nd_epoch]
  225.         image_testing_before_2nd_epoch = create_image(X_test_normalized, y_pred_binary_after_2nd_epoch, label_colors_testing)
  226.  
  227.     if epoch >= epochs-1:
  228.         print(f"HERE HERE Epoch: {epoch}, Epochs: {epochs}\n")
  229.         sys.stdout.flush()
  230.  
  231.         # Iterate through new persons
  232.         for idx, personNEW_results in enumerate(new_persons_results, start=1):
  233.             # Ensure that personNEW_results has the same number of features as the model expects
  234.             assert len(personNEW_results) == len(X_train[0]), "Mismatch in the number of features."
  235.  
  236.             personNEW_results_normalized = (np.array(personNEW_results) - min_values) / (max_values - min_values)
  237.  
  238.             personNEW_prediction = model.predict(np.array([personNEW_results_normalized]))
  239.             personNEW_label = 1 if personNEW_prediction >= 0.5 else 0
  240.             y_pred_after_50_epochs = model.predict(X_test_normalized)
  241.             y_pred_binary_after_50_epochs = [1 if pred >= 0.5 else 0 for pred in y_pred_after_50_epochs]
  242.             image_testing_after_50_epochs = create_image(X_test_normalized, y_pred_binary_after_50_epochs, label_colors_testing)
  243.  
  244.             # Create an image for the new person
  245.             image_personNEW = create_imageN([personNEW_results_normalized], [personNEW_label], label_colors)
  246.  
  247.             # Display the images
  248.             plt.figure(figsize=(5, 5))
  249.             plt.imshow(image_personNEW)
  250.             plt.title(f"New Person {idx}\nLabel: {personNEW_label}, Prediction: {personNEW_prediction}")
  251.             plt.axis("off")
  252.             plt.show()
  253.  
  254. # Display the images
  255. plt.figure(figsize=(25, 15))
  256. plt.subplot(2, 2, 1)
  257. plt.imshow(image_training)
  258. plt.title("Training Data")
  259. plt.axis("off")
  260.  
  261. plt.subplot(2, 2, 2)
  262. plt.imshow(image_testing_before_2nd_epoch)
  263. plt.title("Testing Data (2nd Epoch)")
  264. plt.axis("off")
  265.  
  266. plt.subplot(2, 2, 3)
  267. plt.imshow(image_testing_after_50_epochs)
  268. plt.title(f"Testing Data ({epochs} Epochs)")
  269. plt.axis("off")
  270.  
  271. plt.subplot(2, 2, 4)
  272. plt.imshow(image_personNEW)
  273. plt.title(f"New Person\nLabel: {personNEW_label},[{personNEW_prediction}]")
  274. plt.axis("off")
  275.  
  276. # Plot accuracy history
  277. plt.figure(figsize=(12, 5))
  278. plt.plot(range(1, epochs + 1), accuracy_history, marker='o')
  279. plt.title('Accuracy Over Epochs')
  280. plt.xlabel('Epochs')
  281. plt.ylabel('Accuracy')
  282. plt.grid()
  283.  
  284. # Print normalized data
  285. print("Normalized PersonNEW Data:")
  286. print(personNEW_results_normalized)
  287.  
  288. plt.show()
  289.  
  290. print("X_train before normalization:")
  291. print(X_train)
  292. print("X_test before normalization:")
  293. print(X_test)
  294.  
  295. import seaborn as sns
  296.  
  297. print("KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK")
  298. print(X_test)
  299. print("HHHHHHHHHHHHHHHHHHHHHHHHHHHHHH")
  300. print(X_train)
  301. print("LLLLLLLLLLLLLLLLLLLLLLLLLLLLL")
  302.  
  303. from sklearn.metrics import confusion_matrix
  304. from tensorflow.keras.utils import to_categorical
  305.  
  306. np.set_printoptions(threshold=np.inf, precision=4, suppress=True)
  307.  
  308. # Generate predictions from the model
  309. predictions = (model.predict(X_test_normalized) > 0.5).astype(int)
  310.  
  311. # Convert y_test to a numpy array and then to binary labels
  312. y_test_array = np.array(y_test)  # Convert y_test to a numpy array
  313. y_test_binary = (y_test_array > 0.5).astype(int)  # Convert to binary
  314.  
  315. # Compute the confusion matrix
  316. conf_matrix = confusion_matrix(y_test_binary, predictions)
  317.  
  318. # Evaluate the model's performance
  319. accuracy = accuracy_score(y_test_binary, predictions)
  320. precision = precision_score(y_test_binary, predictions)
  321. recall = recall_score(y_test_binary, predictions)
  322. f1 = f1_score(y_test_binary, predictions)
  323.  
  324. # Display the confusion matrix
  325. sns.heatmap(conf_matrix, annot=True, fmt='d', cmap='Blues')
  326. plt.xlabel('Predicted')
  327. plt.ylabel('Actual')
  328. plt.title('Confusion Matrix')
  329. plt.show()
  330.  
  331. print(f"Accuracy: {accuracy:.4f}")
  332. print(f"Precision: {precision:.4f}")
  333. print(f"Recall: {recall:.4f}")
  334. print(f"F1 Score: {f1:.4f}")
  335.  
  336. print(f"Confusion Matrix2122:\n{conf_matrix}")
  337.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement