Advertisement
max2201111

posledni anejlepsi VK very good CM almost diagonal

Jun 25th, 2024
605
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 13.84 KB | Science | 0 0
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import tensorflow as tf
  4. from tqdm.notebook import tqdm_notebook
  5. from IPython.display import display, Javascript
  6. from google.colab import files
  7. import os
  8. import shutil
  9. import ast
  10. from sklearn.metrics import confusion_matrix, accuracy_score, precision_score, recall_score, f1_score
  11. import seaborn as sns
  12. from skimage.transform import resize
  13.  
  14. display(Javascript('IPython.OutputArea.auto_scroll_threshold = 9999;'))
  15.  
  16. label_colors = {0: [0, 128, 0], 1: [255, 0, 0]}
  17. label_colors_testing = {0: [0, 128, 0], 1: [255, 0, 0]}
  18.  
  19. %matplotlib inline
  20.  
  21. def create_image(data, predictions, label_colors):
  22.     num_rows, num_columns = len(data), len(data[0])
  23.     image = np.zeros((num_rows, num_columns + 1, 3), dtype=np.uint8)
  24.     min_val = np.min(data)
  25.     max_val = np.max(data)
  26.     for i in range(num_rows):
  27.         for j in range(num_columns):
  28.             pixel_value = int(np.interp(data[i][j], [min_val, max_val], [0, 255]))
  29.             image[i, j] = np.array([pixel_value] * 3)
  30.         image[i, -1] = label_colors[predictions[i]]
  31.     return image
  32.  
  33. def create_imageN(data, predictions, label_colors):
  34.     num_training_rows = len(data)
  35.     num_columns = len(data[0])
  36.     image_training = np.zeros((num_training_rows, num_columns + 1, 3), dtype=np.uint8)
  37.     for i in range(num_training_rows):
  38.         for j in range(num_columns):
  39.             pixel_value = int(np.interp(data[i][j], [-3, 3], [0, 255]))
  40.             image_training[i, j] = np.array([pixel_value] * 3)
  41.         image_training[i, -1] = label_colors[int(predictions[i])]
  42.     return image_training
  43.  
  44. def create_cnn_model(input_shape):
  45.     model = tf.keras.Sequential([
  46.         tf.keras.layers.InputLayer(input_shape=input_shape),
  47.         tf.keras.layers.Conv2D(filters=32, kernel_size=(3, 3), activation='relu'),
  48.         tf.keras.layers.MaxPooling2D(pool_size=(2, 2)),
  49.         tf.keras.layers.Flatten(),
  50.         tf.keras.layers.Dense(64, activation='relu'),
  51.         tf.keras.layers.Dense(1, activation='sigmoid')
  52.     ])
  53.     model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
  54.     return model
  55.  
  56. def create_dnn_model(input_shape):
  57.     model = tf.keras.Sequential([
  58.         tf.keras.layers.Dense(128, activation='relu', input_shape=(input_shape,)),
  59.         tf.keras.layers.Dense(64, activation='relu'),
  60.         tf.keras.layers.Dense(1, activation='sigmoid')
  61.     ])
  62.     model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
  63.     return model
  64.  
  65. new_persons_results = [
  66.     [0.030391238492519845, 0.23021081913032299, 0.4743575198860915, 0.639395348276238],
  67.     [0.19790381537769108, 0.37639843860181527, 0.5676528538456297, 0.716530820399044],
  68.     [0.0035245462826666075, 0.23127629815305784, 0.4802171123709532, 0.6591272725083992],
  69.     [0.059230621364548486, 0.24424510845680134, 0.442553808602372, 0.6891856336835676],
  70.     [0.05536813173866345, 0.2538888869331579, 0.47861285542743165, 0.6200559751500355],
  71.     [0.1300359168058454, 0.38443677757577344, 0.5957238735056223, 0.795823160451845],
  72.     [0.1743368240338569, 0.3713129035302336, 0.5640350202165867, 0.7213527928848786],
  73.     [0.09173335232875372, 0.2559096689549753, 0.49527436563146954, 0.6970388573439903],
  74.     [0.015235204378572087, 0.2284904031445293, 0.46613902406934005, 0.6917336579549159],
  75.     [0.0011416656054787145, 0.24567669307188245, 0.4388400949432476, 0.667323193441009],
  76.     [0.11776711, 0.17521301, 0.5074825, 0.8509191],
  77.     [0.12314088, 0.27565651, 0.52214202, 0.77386896],
  78. ]
  79.  
  80. uploaded = files.upload()
  81. for filename in uploaded.keys():
  82.     original_path = f"/content/{filename}"
  83.     destination_path = os.path.join("/content/", "DATA2")
  84.     shutil.move(original_path, destination_path)
  85.     print(f"Soubor {filename} byl přesunut do {destination_path}")
  86.  
  87. file_path = '/content/DATA2'
  88. with open(file_path, 'r') as file:
  89.     code = file.read()
  90.  
  91. A_list = ast.literal_eval(code)
  92. A = np.array(A_list)
  93.  
  94. labels = [results[-1] for results in A]
  95. data = [results[:-1] for results in A]
  96.  
  97. num_training_rows = 50
  98. num_testing_rows = 50
  99. X_train, X_test, y_train, y_test = data[:num_training_rows], data[num_training_rows:num_training_rows + num_testing_rows], labels[:num_training_rows], labels[num_training_rows:num_training_rows + num_testing_rows]
  100.  
  101. X_train, X_test, y_train, y_test = data[:num_training_rows], data[:num_testing_rows], labels[:num_training_rows], labels[:num_testing_rows]
  102.  
  103.  
  104.  
  105. mean_values = np.mean(X_train, axis=0)
  106. std_values = np.std(X_train, axis=0)
  107. X_train_normalized = (X_train - mean_values) / std_values
  108. X_test_normalized = (X_test - mean_values) / std_values
  109.  
  110. # Verify normalization
  111. print("Mean of X_train_normalized (should be close to 0):", np.mean(X_train_normalized, axis=0))
  112. print("Std of X_train_normalized (should be close to 1):", np.std(X_train_normalized, axis=0))
  113.  
  114. # Generate images from normalized data for CNN
  115. image_training = create_imageN(X_train_normalized, y_train, label_colors)
  116. image_testing = create_imageN(X_test_normalized, y_test, label_colors_testing)
  117.  
  118. # Resize images to a fixed size for CNN input
  119. image_training_resized = [resize(img[:, :-1], (100, 100, 3)) for img in image_training]
  120. image_testing_resized = [resize(img[:, :-1], (100, 100, 3)) for img in image_testing]
  121.  
  122. # Reshape images for CNN
  123. X_train_cnn = np.array(image_training_resized)
  124. X_test_cnn = np.array(image_testing_resized)
  125.  
  126. mean_train_cnn = np.mean(X_train_cnn, axis=(0, 1, 2))
  127. std_train_cnn = np.std(X_train_cnn, axis=(0, 1, 2))
  128. X_train_cnn_normalized = (X_train_cnn - mean_train_cnn) / std_train_cnn
  129. X_test_cnn_normalized = (X_test_cnn - mean_train_cnn) / std_train_cnn
  130.  
  131. # DNN Model
  132. dnn_model = create_dnn_model(len(X_train[0]))
  133.  
  134. # Training DNN Model
  135. dnn_accuracy_history = []
  136. epochs = 50
  137.  
  138. for epoch in tqdm_notebook(range(epochs)):
  139.     history_dnn = dnn_model.fit(X_train_normalized, np.array(y_train), epochs=1, verbose=0, shuffle=False)
  140.     dnn_accuracy_history.append(history_dnn.history['accuracy'][0])
  141.  
  142.     if epoch == 1:
  143.         y_pred_after_2nd_epoch_dnn = dnn_model.predict(X_test_normalized)
  144.         y_pred_binary_after_2nd_epoch_dnn = [1 if pred >= 0.5 else 0 for pred in y_pred_after_2nd_epoch_dnn]
  145.         image_testing_before_2nd_epoch_dnn = create_image(X_test_normalized, y_pred_binary_after_2nd_epoch_dnn, label_colors_testing)
  146.  
  147.     if epoch >= epochs - 1:
  148.         print(f"HERE HERE Epoch: {epoch}, Epochs: {epochs}\n")
  149.  
  150.         # Iterate through new persons
  151.         for idx, personNEW_results in enumerate(new_persons_results, start=1):
  152.             assert len(personNEW_results) == len(X_train[0]), "Mismatch in the number of features."
  153.             personNEW_results_normalized = (np.array(personNEW_results) - mean_values) / std_values
  154.             personNEW_prediction_dnn = dnn_model.predict(np.array([personNEW_results_normalized]))
  155.             personNEW_label_dnn = 1 if personNEW_prediction_dnn >= 0.5 else 0
  156.             y_pred_after_50_epochs_dnn = dnn_model.predict(X_test_normalized)
  157.             y_pred_binary_after_50_epochs_dnn = [1 if pred >= 0.5 else 0 for pred in y_pred_after_50_epochs_dnn]
  158.             image_testing_after_50_epochs_dnn = create_image(X_test_normalized, y_pred_binary_after_50_epochs_dnn, label_colors_testing)
  159.             image_personNEW_dnn = create_imageN([personNEW_results_normalized], [personNEW_label_dnn], label_colors)
  160.             plt.figure(figsize=(5, 5))
  161.             plt.imshow(image_personNEW_dnn)
  162.             plt.title(f"New Person {idx} - DNN\nLabel: {personNEW_label_dnn}, Prediction: {personNEW_prediction_dnn}")
  163.             plt.axis("off")
  164.             plt.show()
  165.  
  166. # CNN Model
  167. cnn_model = create_cnn_model((100, 100, 3))
  168.  
  169. # Training CNN Model
  170. cnn_accuracy_history = []
  171.  
  172. for epoch in tqdm_notebook(range(epochs)):
  173.     history_cnn = cnn_model.fit(X_train_cnn_normalized, np.array(y_train), epochs=1, verbose=0, shuffle=False)
  174.     cnn_accuracy_history.append(history_cnn.history['accuracy'][0])
  175.  
  176.     if epoch == 1:
  177.         y_pred_after_2nd_epoch_cnn = cnn_model.predict(X_test_cnn_normalized)
  178.         y_pred_binary_after_2nd_epoch_cnn = [1 if pred >= 0.5 else 0 for pred in y_pred_after_2nd_epoch_cnn]
  179.         image_testing_before_2nd_epoch_cnn = create_image(X_test_normalized, y_pred_binary_after_2nd_epoch_cnn, label_colors_testing)
  180.  
  181.     if epoch >= epochs - 1:
  182.         print(f"HERE HERE Epoch: {epoch}, Epochs: {epochs}\n")
  183.  
  184.         # Iterate through new persons
  185.         for idx, personNEW_results in enumerate(new_persons_results, start=1):
  186.             assert len(personNEW_results) == len(X_train[0]), "Mismatch in the number of features."
  187.             personNEW_results_normalized = (np.array(personNEW_results) - mean_values) / std_values
  188.             image_personNEW = create_imageN([personNEW_results_normalized], [0], label_colors)
  189.             image_personNEW_resized = resize(image_personNEW[:, :-1], (100, 100, 3))
  190.             image_personNEW_resized_normalized = (image_personNEW_resized - mean_train_cnn) / std_train_cnn  # Normalize new person image
  191.             personNEW_prediction_cnn = cnn_model.predict(np.array([image_personNEW_resized_normalized]))
  192.             personNEW_label_cnn = 1 if personNEW_prediction_cnn >= 0.5 else 0
  193.             y_pred_after_epochs_cnn = cnn_model.predict(X_test_cnn_normalized)
  194.             y_pred_binary_after_epochs_cnn = [1 if pred >= 0.5 else 0 for pred in y_pred_after_epochs_cnn]
  195.             image_testing_after_epochs_cnn = create_image(X_test_normalized, y_pred_binary_after_epochs_cnn, label_colors_testing)
  196.             image_personNEW_cnn = create_imageN([personNEW_results_normalized], [personNEW_label_cnn], label_colors)
  197.             plt.figure(figsize=(5, 5))
  198.             plt.imshow(image_personNEW_cnn)
  199.             plt.title(f"New Person {idx} - CNN\nLabel: {personNEW_label_cnn}, Prediction: {personNEW_prediction_cnn}")
  200.             plt.axis("off")
  201.             plt.show()
  202.  
  203. # Display the images
  204. plt.figure(figsize=(25, 15))
  205. plt.subplot(2, 2, 1)
  206. plt.imshow(image_training)
  207. plt.title("Training Data")
  208. plt.axis("off")
  209.  
  210. plt.subplot(2, 2, 2)
  211. plt.imshow(image_testing_before_2nd_epoch_dnn)
  212. plt.title("Testing Data (2nd Epoch) - DNN")
  213. plt.axis("off")
  214.  
  215. plt.subplot(2, 2, 3)
  216. plt.imshow(image_testing_after_50_epochs_dnn)
  217. plt.title(f"Testing Data ({epochs} Epochs) - DNN")
  218. plt.axis("off")
  219.  
  220. plt.subplot(2, 2, 4)
  221. plt.imshow(image_personNEW_dnn)
  222. plt.title(f"New Person - DNN\nLabel: {personNEW_label_dnn},[{personNEW_prediction_dnn}]")
  223. plt.axis("off")
  224.  
  225. plt.figure(figsize=(12, 5))
  226. plt.plot(range(1, epochs + 1), dnn_accuracy_history, marker='o')
  227. plt.title('DNN Accuracy Over Epochs')
  228. plt.xlabel('Epochs')
  229. plt.ylabel('Accuracy')
  230. plt.grid()
  231.  
  232. plt.figure(figsize=(25, 15))
  233. plt.subplot(2, 2, 1)
  234. plt.imshow(image_training)
  235. plt.title("Training Data")
  236. plt.axis("off")
  237.  
  238. plt.subplot(2, 2, 2)
  239. plt.imshow(image_testing_before_2nd_epoch_cnn)
  240. plt.title("Testing Data (2nd Epoch) - CNN")
  241. plt.axis("off")
  242.  
  243. plt.subplot(2, 2, 3)
  244. plt.imshow(image_testing_after_epochs_cnn)
  245. plt.title(f"Testing Data ({epochs} Epochs) - CNN")
  246. plt.axis("off")
  247.  
  248. plt.subplot(2, 2, 4)
  249. plt.imshow(image_personNEW_cnn)
  250. plt.title(f"New Person - CNN\nLabel: {personNEW_label_cnn},[{personNEW_prediction_cnn}]")
  251. plt.axis("off")
  252.  
  253. plt.figure(figsize=(12, 5))
  254. plt.plot(range(1, epochs + 1), cnn_accuracy_history, marker='o')
  255. plt.title('CNN Accuracy Over Epochs')
  256. plt.xlabel('Epochs')
  257. plt.ylabel('Accuracy')
  258. plt.grid()
  259.  
  260. # Confusion Matrix and Performance Metrics for DNN
  261. dnn_predictions = (dnn_model.predict(X_test_normalized) > 0.5).astype(int)
  262. dnn_conf_matrix = confusion_matrix(y_test, dnn_predictions)
  263. print(f"Confusion Matrix for DNN:\n{dnn_conf_matrix}")
  264. dnn_accuracy = accuracy_score(y_test, dnn_predictions)
  265. dnn_precision = precision_score(y_test, dnn_predictions)
  266. dnn_recall = recall_score(y_test, dnn_predictions)
  267. dnn_f1 = f1_score(y_test, dnn_predictions)
  268. print(f"DNN Accuracy: {dnn_accuracy:.4f}")
  269. print(f"DNN Precision: {dnn_precision:.4f}")
  270. print(f"DNN Recall: {dnn_recall:.4f}")
  271. print(f"DNN F1 Score: {dnn_f1:.4f}")
  272.  
  273. # Confusion Matrix and Performance Metrics for CNN
  274. cnn_predictions = (cnn_model.predict(X_test_cnn_normalized) > 0.5).astype(int)
  275. cnn_conf_matrix = confusion_matrix(y_test, cnn_predictions)
  276. print(f"Confusion Matrix for CNN:\n{cnn_conf_matrix}")
  277. cnn_accuracy = accuracy_score(y_test, cnn_predictions)
  278. cnn_precision = precision_score(y_test, cnn_predictions)
  279. cnn_recall = recall_score(y_test, cnn_predictions)
  280. cnn_f1 = f1_score(y_test, cnn_predictions)
  281. print(f"CNN Accuracy: {cnn_accuracy:.4f}")
  282. print(f"CNN Precision: {cnn_precision:.4f}")
  283. print(f"CNN Recall: {cnn_recall:.4f}")
  284. print(f"CNN F1 Score: {cnn_f1:.4f}")
  285.  
  286. # Display confusion matrices
  287. plt.figure(figsize=(12, 5))
  288.  
  289. plt.subplot(1, 2, 1)
  290. sns.heatmap(dnn_conf_matrix, annot=True, fmt='d', cmap='Blues')
  291. plt.xlabel('Predicted')
  292. plt.ylabel('Actual')
  293. plt.title('DNN Confusion Matrix')
  294.  
  295. plt.subplot(1, 2, 2)
  296. sns.heatmap(cnn_conf_matrix, annot=True, fmt='d', cmap='Blues')
  297. plt.xlabel('Predicted')
  298. plt.ylabel('Actual')
  299. plt.title('CNN Confusion Matrix')
  300.  
  301. plt.show()
  302.  
  303. # Optimalizace nového vektoru pro predikci co nejblíže 0.52
  304. target_prediction = 0.52
  305. input_shape = 4
  306. new_vector = np.random.randn(input_shape)
  307. new_vector = tf.Variable(new_vector, dtype=tf.float32)
  308.  
  309. optimizer = tf.optimizers.Adam(learning_rate=0.1)
  310.  
  311. def loss_function():
  312.     prediction = dnn_model(tf.reshape(new_vector, (1, -1)))
  313.     return tf.abs(prediction - target_prediction)
  314.  
  315. # Gradientní sestup
  316. for _ in range(1000):
  317.     optimizer.minimize(loss_function, [new_vector])
  318.  
  319. # Denormalizace výsledného vektoru
  320. result_vector = new_vector.numpy()
  321. denormalized_vector = result_vector * std_values + mean_values
  322. result_prediction = dnn_model.predict(result_vector.reshape(1, -1))
  323.  
  324. print("Výsledný vektor (normalizovaný):", result_vector)
  325. print("Výsledný vektor (denormalizovaný):", denormalized_vector)
  326. print("Predikce výsledného vektoru:", result_prediction)
  327.  
  328. print(X_test_normalized)
  329.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement