Advertisement
max2201111

VK the best confusion matrix DNN CNN

Jun 20th, 2024
641
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.79 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.  
  13. display(Javascript('IPython.OutputArea.auto_scroll_threshold = 9999;'))
  14.  
  15. label_colors = {0: [0, 128, 0], 1: [255, 0, 0]}
  16. label_colors_testing = {0: [0, 128, 0], 1: [255, 0, 0]}
  17.  
  18. %matplotlib inline
  19.  
  20. def create_image(data, predictions, label_colors):
  21.     num_rows, num_columns = len(data), len(data[0])
  22.     image = np.zeros((num_rows, num_columns + 1, 3), dtype=np.uint8)
  23.     min_val = np.min(data)
  24.     max_val = np.max(data)
  25.     for i in range(num_rows):
  26.         for j in range(num_columns):
  27.             pixel_value = int(np.interp(data[i][j], [min_val, max_val], [0, 255]))
  28.             image[i, j] = np.array([pixel_value] * 3)
  29.         image[i, -1] = label_colors[predictions[i]]
  30.     return image
  31.  
  32. def create_imageN(data, predictions, label_colors=None):
  33.     num_training_rows = len(data)
  34.     num_columns = len(data[0])
  35.     image_training = np.zeros((num_training_rows, num_columns + 1, 3), dtype=np.uint8)
  36.     for i in range(num_training_rows):
  37.         for j in range(num_columns):
  38.             pixel_value = int(np.interp(data[i][j], [-3, 3], [0, 255]))
  39.             image_training[i, j] = np.array([pixel_value] * 3)
  40.         if label_colors is not None:
  41.             image_training[i, -1] = label_colors[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.Reshape((input_shape[0], 1)),
  48.         tf.keras.layers.Conv1D(filters=32, kernel_size=2, activation='relu'),
  49.         tf.keras.layers.MaxPooling1D(pool_size=2),
  50.         tf.keras.layers.Flatten(),
  51.         tf.keras.layers.Dense(64, activation='relu'),
  52.         tf.keras.layers.Dense(1, activation='sigmoid')
  53.     ])
  54.     model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
  55.     return model
  56.  
  57. uploaded = files.upload()
  58. for filename in uploaded.keys():
  59.     original_path = f"/content/{filename}"
  60.     destination_path = os.path.join("/content/", "/content/DATA2")
  61.     shutil.move(original_path, destination_path)
  62.     print(f"Soubor {filename} byl přesunut do {destination_path}")
  63.  
  64. file_path = '/content/DATA2'
  65. with open(file_path, 'r') as file:
  66.     code = file.read()
  67.  
  68. A_list = ast.literal_eval(code)
  69. A = np.array(A_list)
  70.  
  71. labels = [results[-1] for results in A]
  72. data = [results[:-1] for results in A]
  73.  
  74. num_training_rows = 50
  75. num_testing_rows = 50
  76. X_train, X_test, y_train, y_test = data[:num_training_rows], data[:num_testing_rows], labels[:num_training_rows], labels[:num_testing_rows]
  77.  
  78. mean_values = np.mean(X_train, axis=0)
  79. std_values = np.std(X_train, axis=0)
  80. X_train_normalized = (X_train - mean_values) / std_values
  81. X_test_normalized = (X_test - mean_values) / std_values
  82.  
  83. # DNN Model
  84. dnn_model = tf.keras.Sequential([
  85.     tf.keras.layers.Dense(128, activation='relu', input_shape=(len(X_train[0]),)),
  86.     tf.keras.layers.Dense(64, activation='relu'),
  87.     tf.keras.layers.Dense(1, activation='sigmoid')
  88. ])
  89. dnn_model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
  90.  
  91. # Training DNN Model
  92. dnn_accuracy_history = []
  93. epochs = 600
  94.  
  95. for epoch in tqdm_notebook(range(epochs)):
  96.     history_dnn = dnn_model.fit(X_train_normalized, np.array(y_train), epochs=1, verbose=0, shuffle=False)
  97.     dnn_accuracy_history.append(history_dnn.history['accuracy'][0])
  98.  
  99.     if epoch == 1:
  100.         y_pred_after_2nd_epoch_dnn = dnn_model.predict(X_test_normalized)
  101.         y_pred_binary_after_2nd_epoch_dnn = [1 if pred >= 0.5 else 0 for pred in y_pred_after_2nd_epoch_dnn]
  102.         image_testing_before_2nd_epoch_dnn = create_image(X_test_normalized, y_pred_binary_after_2nd_epoch_dnn, label_colors_testing)
  103.  
  104.     if epoch >= epochs-1:
  105.         print(f"HERE HERE Epoch: {epoch}, Epochs: {epochs}\n")
  106.         sys.stdout.flush()
  107.  
  108.         # Iterate through new persons
  109.         for idx, personNEW_results in enumerate(new_persons_results, start=1):
  110.             assert len(personNEW_results) == len(X_train[0]), "Mismatch in the number of features."
  111.             personNEW_results_normalized = (np.array(personNEW_results) - mean_values) / std_values
  112.             personNEW_prediction_dnn = dnn_model.predict(np.array([personNEW_results_normalized]))
  113.             personNEW_label_dnn = 1 if personNEW_prediction_dnn >= 0.5 else 0
  114.             y_pred_after_50_epochs_dnn = dnn_model.predict(X_test_normalized)
  115.             y_pred_binary_after_50_epochs_dnn = [1 if pred >= 0.5 else 0 for pred in y_pred_after_50_epochs_dnn]
  116.             image_testing_after_50_epochs_dnn = create_image(X_test_normalized, y_pred_binary_after_50_epochs_dnn, label_colors_testing)
  117.             image_personNEW_dnn = create_imageN([personNEW_results_normalized], [personNEW_label_dnn], label_colors)
  118.             plt.figure(figsize=(5, 5))
  119.             plt.imshow(image_personNEW_dnn)
  120.             plt.title(f"New Person {idx} - DNN\nLabel: {personNEW_label_dnn}, Prediction: {personNEW_prediction_dnn}")
  121.             plt.axis("off")
  122.             plt.show()
  123.  
  124. # CNN Model
  125. cnn_model = create_cnn_model((len(X_train[0]), 1))
  126.  
  127. # Preparing data for CNN
  128. X_train_normalized_cnn = X_train_normalized.reshape((X_train_normalized.shape[0], X_train_normalized.shape[1], 1))
  129. X_test_normalized_cnn = X_test_normalized.reshape((X_test_normalized.shape[0], X_test_normalized.shape[1], 1))
  130.  
  131. # Training CNN Model
  132. cnn_accuracy_history = []
  133.  
  134. for epoch in tqdm_notebook(range(epochs)):
  135.     history_cnn = cnn_model.fit(X_train_normalized_cnn, np.array(y_train), epochs=1, verbose=0, shuffle=False)
  136.     cnn_accuracy_history.append(history_cnn.history['accuracy'][0])
  137.  
  138.     if epoch == 1:
  139.         y_pred_after_2nd_epoch_cnn = cnn_model.predict(X_test_normalized_cnn)
  140.         y_pred_binary_after_2nd_epoch_cnn = [1 if pred >= 0.5 else 0 for pred in y_pred_after_2nd_epoch_cnn]
  141.         image_testing_before_2nd_epoch_cnn = create_image(X_test_normalized, y_pred_binary_after_2nd_epoch_cnn, label_colors_testing)
  142.  
  143.     if epoch >= epochs-1:
  144.         print(f"HERE HERE Epoch: {epoch}, Epochs: {epochs}\n")
  145.         sys.stdout.flush()
  146.  
  147.         # Iterate through new persons
  148.         for idx, personNEW_results in enumerate(new_persons_results, start=1):
  149.             assert len(personNEW_results) == len(X_train[0]), "Mismatch in the number of features."
  150.             personNEW_results_normalized = (np.array(personNEW_results) - mean_values) / std_values
  151.             personNEW_results_normalized_cnn = personNEW_results_normalized.reshape((len(personNEW_results_normalized), 1))
  152.             personNEW_prediction_cnn = cnn_model.predict(np.array([personNEW_results_normalized_cnn]))
  153.             personNEW_label_cnn = 1 if personNEW_prediction_cnn >= 0.5 else 0
  154.             y_pred_after_50_epochs_cnn = cnn_model.predict(X_test_normalized_cnn)
  155.             y_pred_binary_after_50_epochs_cnn = [1 if pred >= 0.5 else 0 for pred in y_pred_after_50_epochs_cnn]
  156.             image_testing_after_50_epochs_cnn = create_image(X_test_normalized, y_pred_binary_after_50_epochs_cnn, label_colors_testing)
  157.             image_personNEW_cnn = create_imageN([personNEW_results_normalized], [personNEW_label_cnn], label_colors)
  158.             plt.figure(figsize=(5, 5))
  159.             plt.imshow(image_personNEW_cnn)
  160.             plt.title(f"New Person {idx} - CNN\nLabel: {personNEW_label_cnn}, Prediction: {personNEW_prediction_cnn}")
  161.             plt.axis("off")
  162.             plt.show()
  163.  
  164. # Display the images
  165. plt.figure(figsize=(25, 15))
  166. plt.subplot(2, 2, 1)
  167. plt.imshow(image_training)
  168. plt.title("Training Data")
  169. plt.axis("off")
  170.  
  171. plt.subplot(2, 2, 2)
  172. plt.imshow(image_testing_before_2nd_epoch_dnn)
  173. plt.title("Testing Data (2nd Epoch) - DNN")
  174. plt.axis("off")
  175.  
  176. plt.subplot(2, 2, 3)
  177. plt.imshow(image_testing_after_50_epochs_dnn)
  178. plt.title(f"Testing Data ({epochs} Epochs) - DNN")
  179. plt.axis("off")
  180.  
  181. plt.subplot(2, 2, 4)
  182. plt.imshow(image_personNEW_dnn)
  183. plt.title(f"New Person - DNN\nLabel: {personNEW_label_dnn},[{personNEW_prediction_dnn}]")
  184. plt.axis("off")
  185.  
  186. plt.figure(figsize=(12, 5))
  187. plt.plot(range(1, epochs + 1), dnn_accuracy_history, marker='o')
  188. plt.title('DNN Accuracy Over Epochs')
  189. plt.xlabel('Epochs')
  190. plt.ylabel('Accuracy')
  191. plt.grid()
  192.  
  193. plt.figure(figsize=(25, 15))
  194. plt.subplot(2, 2, 1)
  195. plt.imshow(image_training)
  196. plt.title("Training Data")
  197. plt.axis("off")
  198.  
  199. plt.subplot(2, 2, 2)
  200. plt.imshow(image_testing_before_2nd_epoch_cnn)
  201. plt.title("Testing Data (2nd Epoch) - CNN")
  202. plt.axis("off")
  203.  
  204. plt.subplot(2, 2, 3)
  205. plt.imshow(image_testing_after_50_epochs_cnn)
  206. plt.title(f"Testing Data ({epochs} Epochs) - CNN")
  207. plt.axis("off")
  208.  
  209. plt.subplot(2, 2, 4)
  210. plt.imshow(image_personNEW_cnn)
  211. plt.title(f"New Person - CNN\nLabel: {personNEW_label_cnn},[{personNEW_prediction_cnn}]")
  212. plt.axis("off")
  213.  
  214. plt.figure(figsize=(12, 5))
  215. plt.plot(range(1, epochs + 1), cnn_accuracy_history, marker='o')
  216. plt.title('CNN Accuracy Over Epochs')
  217. plt.xlabel('Epochs')
  218. plt.ylabel('Accuracy')
  219. plt.grid()
  220.  
  221. # Confusion Matrix and Performance Metrics for DNN
  222. dnn_predictions = (dnn_model.predict(X_test_normalized) > 0.5).astype(int)
  223. dnn_conf_matrix = confusion_matrix(y_test, dnn_predictions)
  224. print(f"Confusion Matrix for DNN:\n{dnn_conf_matrix}")
  225. dnn_accuracy = accuracy_score(y_test, dnn_predictions)
  226. dnn_precision = precision_score(y_test, dnn_predictions)
  227. dnn_recall = recall_score(y_test, dnn_predictions)
  228. dnn_f1 = f1_score(y_test, dnn_predictions)
  229. print(f"DNN Accuracy: {dnn_accuracy:.4f}")
  230. print(f"DNN Precision: {dnn_precision:.4f}")
  231. print(f"DNN Recall: {dnn_recall:.4f}")
  232. print(f"DNN F1 Score: {dnn_f1:.4f}")
  233.  
  234. # Confusion Matrix and Performance Metrics for CNN
  235. cnn_predictions = (cnn_model.predict(X_test_normalized_cnn) > 0.5).astype(int)
  236. cnn_conf_matrix = confusion_matrix(y_test, cnn_predictions)
  237. print(f"Confusion Matrix for CNN:\n{cnn_conf_matrix}")
  238. cnn_accuracy = accuracy_score(y_test, cnn_predictions)
  239. cnn_precision = precision_score(y_test, cnn_predictions)
  240. cnn_recall = recall_score(y_test, cnn_predictions)
  241. cnn_f1 = f1_score(y_test, cnn_predictions)
  242. print(f"CNN Accuracy: {cnn_accuracy:.4f}")
  243. print(f"CNN Precision: {cnn_precision:.4f}")
  244. print(f"CNN Recall: {cnn_recall:.4f}")
  245. print(f"CNN F1 Score: {cnn_f1:.4f}")
  246.  
  247. # Display confusion matrices
  248. plt.figure(figsize=(12, 5))
  249.  
  250. plt.subplot(1, 2, 1)
  251. sns.heatmap(dnn_conf_matrix, annot=True, fmt='d', cmap='Blues')
  252. plt.xlabel('Predicted')
  253. plt.ylabel('Actual')
  254. plt.title('DNN Confusion Matrix')
  255.  
  256. plt.subplot(1, 2, 2)
  257. sns.heatmap(cnn_conf_matrix, annot=True, fmt='d', cmap='Blues')
  258. plt.xlabel('Predicted')
  259. plt.ylabel('Actual')
  260. plt.title('CNN Confusion Matrix')
  261.  
  262. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement