Advertisement
max2201111

OK CNN a DNN matice ale vadny sloupec u Testing data 50 epochs

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