Advertisement
max2201111

konecne OK VK CNN a DNN se vsim vsudy

Jun 26th, 2024
355
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 17.14 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.     min_val = np.min(data)
  38.     max_val = np.max(data)
  39.     for i in range(num_training_rows):
  40.         for j in range(num_columns):
  41.             pixel_value = int(np.interp(data[i][j], [min_val, max_val], [0, 255]))
  42.             image_training[i, j] = np.array([pixel_value] * 3)
  43.         image_training[i, -1] = label_colors[int(predictions[i])]
  44.     return image_training
  45.  
  46. # def create_cnn_model(input_shape):
  47. #     model = tf.keras.Sequential([
  48. #         tf.keras.layers.InputLayer(input_shape=input_shape),
  49. #         tf.keras.layers.Conv2D(filters=32, kernel_size=(3, 3), activation='relu'),
  50. #         tf.keras.layers.MaxPooling2D(pool_size=(2, 2)),
  51. #         tf.keras.layers.Flatten(),
  52. #         tf.keras.layers.Dense(64, activation='relu'),
  53. #         tf.keras.layers.Dense(1, activation='sigmoid')
  54. #     ])
  55. #     model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
  56. #     return model
  57.  
  58. def create_cnn_model(input_shape):
  59.     model = tf.keras.Sequential([
  60.         tf.keras.layers.InputLayer(input_shape=input_shape),
  61.         tf.keras.layers.Conv2D(filters=32, kernel_size=(3, 3), activation='relu'),
  62.         tf.keras.layers.MaxPooling2D(pool_size=(2, 2)),
  63.         tf.keras.layers.Dropout(0.25),
  64.         tf.keras.layers.Conv2D(filters=64, kernel_size=(3, 3), activation='relu'),
  65.         tf.keras.layers.MaxPooling2D(pool_size=(2, 2)),
  66.         tf.keras.layers.Dropout(0.25),
  67.         tf.keras.layers.Conv2D(filters=128, kernel_size=(3, 3), activation='relu'),
  68.         tf.keras.layers.MaxPooling2D(pool_size=(2, 2)),
  69.         tf.keras.layers.Dropout(0.25),
  70.         tf.keras.layers.Conv2D(filters=256, kernel_size=(3, 3), activation='relu'),
  71.         tf.keras.layers.MaxPooling2D(pool_size=(2, 2)),
  72.         tf.keras.layers.Flatten(),
  73.         tf.keras.layers.Dense(512, activation='relu'),
  74.         tf.keras.layers.Dropout(0.5),
  75.         tf.keras.layers.Dense(64, activation='relu'),
  76.         tf.keras.layers.Dense(1, activation='sigmoid')
  77.     ])
  78.     model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
  79.     return model
  80.  
  81.  
  82. def create_dnn_model(input_shape):
  83.     model = tf.keras.Sequential([
  84.         tf.keras.layers.Dense(128, activation='relu', input_shape=(input_shape,)),
  85.         tf.keras.layers.Dense(64, activation='relu'),
  86.         tf.keras.layers.Dense(1, activation='sigmoid')
  87.     ])
  88.     model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
  89.     return model
  90.  
  91. new_persons_results = [
  92.     [0.030391238492519845, 0.23021081913032299, 0.4743575198860915, 0.639395348276238],
  93.     [0.19790381537769108, 0.37639843860181527, 0.5676528538456297, 0.716530820399044],
  94.     [0.0035245462826666075, 0.23127629815305784, 0.4802171123709532, 0.6591272725083992],
  95.     [0.059230621364548486, 0.24424510845680134, 0.442553808602372, 0.6891856336835676],
  96.     [0.05536813173866345, 0.2538888869331579, 0.47861285542743165, 0.6200559751500355],
  97.     [0.1300359168058454, 0.38443677757577344, 0.5957238735056223, 0.795823160451845],
  98.     [0.1743368240338569, 0.3713129035302336, 0.5640350202165867, 0.7213527928848786],
  99.     [0.09173335232875372, 0.2559096689549753, 0.49527436563146954, 0.6970388573439903],
  100.     [0.015235204378572087, 0.2284904031445293, 0.46613902406934005, 0.6917336579549159],
  101.     [0.0011416656054787145, 0.24567669307188245, 0.4388400949432476, 0.667323193441009],
  102.     [0.11776711, 0.17521301, 0.5074825, 0.8509191],
  103.     [0.12314088, 0.27565651, 0.52214202, 0.77386896],
  104. ]
  105.  
  106. uploaded = files.upload()
  107. for filename in uploaded.keys():
  108.     original_path = f"/content/{filename}"
  109.     destination_path = os.path.join("/content/", "DATA2")
  110.     shutil.move(original_path, destination_path)
  111.     print(f"Soubor {filename} byl přesunut do {destination_path}")
  112.  
  113. file_path = '/content/DATA2'
  114. with open(file_path, 'r') as file:
  115.     code = file.read()
  116.  
  117. A_list = ast.literal_eval(code)
  118. A = np.array(A_list)
  119.  
  120. labels = [results[-1] for results in A]
  121. data = [results[:-1] for results in A]
  122.  
  123. num_training_rows = 50
  124. num_testing_rows = 30
  125. #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_testing_rows]
  126.  
  127. X_train, X_test, y_train, y_test = data[:num_training_rows], data[:num_testing_rows], labels[:num_training_rows], labels[:num_testing_rows]
  128.  
  129. mean_values = np.mean(X_train, axis=0)
  130. std_values = np.std(X_train, axis=0)
  131. X_train_normalized = (X_train - mean_values) / std_values
  132. X_test_normalized = (X_test - mean_values) / std_values
  133.  
  134. # Verify normalization
  135. print("Mean of X_train_normalized (should be close to 0):", np.mean(X_train_normalized, axis=0))
  136. print("Std of X_train_normalized (should be close to 1):", np.std(X_train_normalized, axis=0))
  137.  
  138. # Generate images from normalized data for CNN
  139. image_training = create_imageN(X_train_normalized, y_train, label_colors)
  140. image_testing = create_imageN(X_test_normalized, y_test, label_colors_testing)
  141.  
  142. # Resize images to a fixed size for CNN input
  143. image_training_resized = [resize(img[:, :-1], (100, 100, 3)) for img in image_training]
  144. image_testing_resized = [resize(img[:, :-1], (100, 100, 3)) for img in image_testing]
  145.  
  146. print(image_training)
  147.  
  148. # Reshape images for CNN
  149. X_train_cnn = np.array(image_training_resized)
  150. X_test_cnn = np.array(image_testing_resized)
  151.  
  152. mean_train_cnn = np.mean(X_train_cnn, axis=(0, 1, 2))
  153. std_train_cnn = np.std(X_train_cnn, axis=(0, 1, 2))
  154. X_train_cnn_normalized = (X_train_cnn - mean_train_cnn) / std_train_cnn
  155. X_test_cnn_normalized = (X_test_cnn - mean_train_cnn) / std_train_cnn
  156.  
  157. # DNN Model
  158. dnn_model = create_dnn_model(len(X_train[0]))
  159.  
  160. # Training DNN Model
  161. dnn_accuracy_history = []
  162. epochs = 150
  163.  
  164. for epoch in tqdm_notebook(range(epochs)):
  165.     history_dnn = dnn_model.fit(X_train_normalized, np.array(y_train), epochs=1, verbose=0, shuffle=False)
  166.     dnn_accuracy_history.append(history_dnn.history['accuracy'][0])
  167.  
  168.     if epoch == 1:
  169.         y_pred_after_2nd_epoch_dnn = dnn_model.predict(X_test_normalized)
  170.         y_pred_binary_after_2nd_epoch_dnn = [1 if pred >= 0.5 else 0 for pred in y_pred_after_2nd_epoch_dnn]
  171.         image_testing_before_2nd_epoch_dnn = create_image(X_test_normalized, y_pred_binary_after_2nd_epoch_dnn, label_colors_testing)
  172.  
  173.     if epoch >= epochs - 1:
  174.         print(f"HERE HERE Epoch: {epoch}, Epochs: {epochs}\n")
  175.  
  176.         # Iterate through new persons
  177.         for idx, personNEW_results in enumerate(new_persons_results, start=1):
  178.             assert len(personNEW_results) == len(X_train[0]), "Mismatch in the number of features."
  179.             personNEW_results_normalized = (np.array(personNEW_results) - mean_values) / std_values
  180.             personNEW_prediction_dnn = dnn_model.predict(np.array([personNEW_results_normalized]))
  181.             personNEW_label_dnn = 1 if personNEW_prediction_dnn >= 0.5 else 0
  182.             y_pred_after_50_epochs_dnn = dnn_model.predict(X_test_normalized)
  183.             y_pred_binary_after_50_epochs_dnn = [1 if pred >= 0.5 else 0 for pred in y_pred_after_50_epochs_dnn]
  184.             image_testing_after_50_epochs_dnn = create_image(X_test_normalized, y_pred_binary_after_50_epochs_dnn, label_colors_testing)
  185.             image_personNEW_dnn = create_imageN([personNEW_results_normalized], [personNEW_label_dnn], label_colors)
  186.             plt.figure(figsize=(5, 5))
  187.             plt.imshow(image_personNEW_dnn)
  188.             plt.title(f"New Person {idx} - DNN\nLabel: {personNEW_label_dnn}, Prediction: {personNEW_prediction_dnn}")
  189.             plt.axis("off")
  190.             plt.show()
  191.  
  192. # CNN Model
  193. cnn_model = create_cnn_model((100, 100, 3))
  194.  
  195. # Training CNN Model
  196. cnn_accuracy_history = []
  197.  
  198. for epoch in tqdm_notebook(range(epochs)):
  199.     history_cnn = cnn_model.fit(X_train_cnn_normalized, np.array(y_train), epochs=1, verbose=0, shuffle=False)
  200.     cnn_accuracy_history.append(history_cnn.history['accuracy'][0])
  201.  
  202.     if epoch == 1:
  203.         y_pred_after_2nd_epoch_cnn = cnn_model.predict(X_test_cnn_normalized)
  204.         y_pred_binary_after_2nd_epoch_cnn = [1 if pred >= 0.5 else 0 for pred in y_pred_after_2nd_epoch_cnn]
  205.         image_testing_before_2nd_epoch_cnn = create_image(X_test_normalized, y_pred_binary_after_2nd_epoch_cnn, label_colors_testing)
  206.  
  207.     if epoch >= epochs - 1:
  208.         print(f"HERE HERE Epoch: {epoch}, Epochs: {epochs}\n")
  209.  
  210.         # Iterate through new persons
  211.         for idx, personNEW_results in enumerate(new_persons_results, start=1):
  212.             assert len(personNEW_results) == len(X_train[0]), "Mismatch in the number of features."
  213.             personNEW_results_normalized = (np.array(personNEW_results) - mean_values) / std_values
  214.             image_personNEW = create_imageN([personNEW_results_normalized], [0], label_colors)
  215.             image_personNEW_resized = resize(image_personNEW[:, :-1], (100, 100, 3))
  216.             image_personNEW_resized_normalized = (image_personNEW_resized - mean_train_cnn) / std_train_cnn  # Normalize new person image
  217.             personNEW_prediction_cnn = cnn_model.predict(np.array([image_personNEW_resized_normalized]))
  218.             personNEW_label_cnn = 1 if personNEW_prediction_cnn >= 0.5 else 0
  219.             y_pred_after_epochs_cnn = cnn_model.predict(X_test_cnn_normalized)
  220.             y_pred_binary_after_epochs_cnn = [1 if pred >= 0.5 else 0 for pred in y_pred_after_epochs_cnn]
  221.             image_testing_after_epochs_cnn = create_image(X_test_normalized, y_pred_binary_after_epochs_cnn, label_colors_testing)
  222.             image_personNEW_cnn = create_imageN([personNEW_results_normalized], [personNEW_label_cnn], label_colors)
  223.             plt.figure(figsize=(5, 5))
  224.             plt.imshow(image_personNEW_cnn)
  225.             plt.title(f"New Person {idx} - CNN\nLabel: {personNEW_label_cnn}, Prediction: {personNEW_prediction_cnn}")
  226.             plt.axis("off")
  227.             plt.show()
  228.  
  229. # Display the images
  230. plt.figure(figsize=(25, 15))
  231. plt.subplot(2, 2, 1)
  232. plt.imshow(image_training)
  233. plt.title("Training Data")
  234. plt.axis("off")
  235.  
  236. plt.subplot(2, 2, 2)
  237. plt.imshow(image_testing_before_2nd_epoch_dnn)
  238. plt.title("Testing Data (2nd Epoch) - DNN")
  239. plt.axis("off")
  240.  
  241. plt.subplot(2, 2, 3)
  242. plt.imshow(image_testing_after_50_epochs_dnn)
  243. plt.title(f"Testing Data ({epochs} Epochs) - DNN")
  244. plt.axis("off")
  245.  
  246. plt.subplot(2, 2, 4)
  247. plt.imshow(image_personNEW_dnn)
  248. plt.title(f"New Person - DNN\nLabel: {personNEW_label_dnn},[{personNEW_prediction_dnn}]")
  249. plt.axis("off")
  250.  
  251. plt.figure(figsize=(12, 5))
  252. plt.plot(range(1, epochs + 1), dnn_accuracy_history, marker='o')
  253. plt.title('DNN Accuracy Over Epochs')
  254. plt.xlabel('Epochs')
  255. plt.ylabel('Accuracy')
  256. plt.grid()
  257.  
  258. plt.figure(figsize=(25, 15))
  259. plt.subplot(2, 2, 1)
  260. plt.imshow(image_training)
  261. plt.title("Training Data")
  262. plt.axis("off")
  263.  
  264. plt.subplot(2, 2, 2)
  265. plt.imshow(image_testing_before_2nd_epoch_cnn)
  266. plt.title("Testing Data (2nd Epoch) - CNN")
  267. plt.axis("off")
  268.  
  269. plt.subplot(2, 2, 3)
  270. plt.imshow(image_testing_after_epochs_cnn)
  271. plt.title(f"Testing Data ({epochs} Epochs) - CNN")
  272. plt.axis("off")
  273.  
  274. plt.subplot(2, 2, 4)
  275. plt.imshow(image_personNEW_cnn)
  276. plt.title(f"New Person - CNN\nLabel: {personNEW_label_cnn},[{personNEW_prediction_cnn}]")
  277. plt.axis("off")
  278.  
  279. plt.figure(figsize=(12, 5))
  280. plt.plot(range(1, epochs + 1), cnn_accuracy_history, marker='o')
  281. plt.title('CNN Accuracy Over Epochs')
  282. plt.xlabel('Epochs')
  283. plt.ylabel('Accuracy')
  284. plt.grid()
  285.  
  286. # Confusion Matrix and Performance Metrics for DNN
  287. dnn_predictions = (dnn_model.predict(X_test_normalized) > 0.5).astype(int)
  288. dnn_conf_matrix = confusion_matrix(y_test, dnn_predictions)
  289. print(f"Confusion Matrix for DNN:\n{dnn_conf_matrix}")
  290. dnn_accuracy = accuracy_score(y_test, dnn_predictions)
  291. dnn_precision = precision_score(y_test, dnn_predictions)
  292. dnn_recall = recall_score(y_test, dnn_predictions)
  293. dnn_f1 = f1_score(y_test, dnn_predictions)
  294. print(f"DNN Accuracy: {dnn_accuracy:.4f}")
  295. print(f"DNN Precision: {dnn_precision:.4f}")
  296. print(f"DNN Recall: {dnn_recall:.4f}")
  297. print(f"DNN F1 Score: {dnn_f1:.4f}")
  298.  
  299. # Confusion Matrix and Performance Metrics for CNN
  300. cnn_predictions = (cnn_model.predict(X_test_cnn_normalized) > 0.5).astype(int)
  301. cnn_conf_matrix = confusion_matrix(y_test, cnn_predictions)
  302. print(f"Confusion Matrix for CNN:\n{cnn_conf_matrix}")
  303. cnn_accuracy = accuracy_score(y_test, cnn_predictions)
  304. cnn_precision = precision_score(y_test, cnn_predictions)
  305. cnn_recall = recall_score(y_test, cnn_predictions)
  306. cnn_f1 = f1_score(y_test, cnn_predictions)
  307. print(f"CNN Accuracy: {cnn_accuracy:.4f}")
  308. print(f"CNN Precision: {cnn_precision:.4f}")
  309. print(f"CNN Recall: {cnn_recall:.4f}")
  310. print(f"CNN F1 Score: {cnn_f1:.4f}")
  311.  
  312. # Display confusion matrices
  313. plt.figure(figsize=(12, 5))
  314.  
  315. plt.subplot(1, 2, 1)
  316. sns.heatmap(dnn_conf_matrix, annot=True, fmt='d', cmap='Blues')
  317. plt.xlabel('Predicted')
  318. plt.ylabel('Actual')
  319. plt.title('DNN Confusion Matrix')
  320.  
  321. plt.subplot(1, 2, 2)
  322. sns.heatmap(cnn_conf_matrix, annot=True, fmt='d', cmap='Blues')
  323. plt.xlabel('Predicted')
  324. plt.ylabel('Actual')
  325. plt.title('CNN Confusion Matrix')
  326.  
  327. plt.show()
  328.  
  329.  
  330. # Optimalizace nového vektoru pro predikci co nejblíže 0.52 a 1.00
  331. target_predictions = [0.52, 1.00]
  332. input_shape = 4
  333.  
  334. results = {}
  335.  
  336. def loss_function(target):
  337.     prediction = dnn_model(tf.reshape(new_vector, (1, -1)))
  338.     return tf.abs(prediction - target)
  339.  
  340. for target in target_predictions:
  341.     new_vector = tf.Variable(np.random.randn(input_shape), dtype=tf.float32)
  342.     optimizer = tf.optimizers.Adam(learning_rate=0.1)
  343.     optimizer.build([new_vector])
  344.    
  345.     for _ in range(1000):
  346.         optimizer.minimize(lambda: loss_function(target), [new_vector])
  347.    
  348.     # Denormalizace výsledného vektoru
  349.     result_vector = new_vector.numpy()
  350.     denormalized_vector = result_vector * std_values + mean_values
  351.     result_prediction = dnn_model.predict(result_vector.reshape(1, -1))
  352.  
  353.     results[target] = {
  354.         "normalized": result_vector,
  355.         "denormalized": denormalized_vector,
  356.         "prediction": result_prediction
  357.     }
  358.    
  359.     print(f"Výsledný vektor (normalizovaný) pro target {target}: {result_vector}")
  360.     print(f"Výsledný vektor (denormalizovaný) pro target {target}: {denormalized_vector}")
  361.     print(f"Predikce výsledného vektoru pro target {target}: {result_prediction}")
  362.  
  363. # Funkce pro vytvoření vstupu pro CNN s 4 šedo-bílo-černými čtverečky a 5. barevným čtverečkem
  364. def create_cnn_input_image(vector, target_shape, prediction):
  365.     image = np.ones(target_shape, dtype=np.float32) * 255  # bílé pozadí
  366.     square_size = target_shape[0] // 3  # velikost čtverců
  367.  
  368.     # Vyplnění 4 čtverečků hodnotami z vektoru (šedo-bílo-černé)
  369.     for i in range(2):
  370.         for j in range(2):
  371.             value = vector[i * 2 + j]
  372.             gray_value = int((value - np.min(vector)) / (np.max(vector) - np.min(vector)) * 255)
  373.             image[i*square_size:(i+1)*square_size, j*square_size:(j+1)*square_size] = gray_value
  374.  
  375.     # 5. čtvereček na základě predikce
  376.     color = [0, 255, 0] if prediction >= 0.5 else [255, 0, 0]
  377.     image[2*square_size:, :square_size] = color  # zelený nebo červený čtvereček
  378.  
  379.     return image
  380.  
  381. # Připravit vstupy pro CNN model
  382. target_shape = (100, 100, 3)
  383. cnn_inputs = {target: create_cnn_input_image(result["denormalized"], target_shape, result["prediction"]) for target, result in results.items()}
  384.  
  385. # Normalizace vstupů pro CNN model
  386. cnn_inputs_normalized = {target: (input_image - mean_train_cnn) / std_train_cnn for target, input_image in cnn_inputs.items()}
  387.  
  388. # Predikce CNN modelu
  389. for target, input_image in cnn_inputs_normalized.items():
  390.     input_image_reshaped = input_image.reshape(1, *target_shape)
  391.     cnn_prediction = cnn_model.predict(input_image_reshaped)
  392.     print(f"Predikce CNN modelu pro target {target}: {cnn_prediction}")
  393.  
  394. # Zobrazení obrazů
  395. for target, input_image in cnn_inputs.items():
  396.     plt.figure(figsize=(5, 5))
  397.     plt.imshow(input_image.astype(np.uint8))
  398.     plt.title(f"Target {target} - CNN Input Image")
  399.     plt.axis("off")
  400.     plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement