Advertisement
max2201111

nefukcni CNN cista 1.000

Jun 27th, 2024
583
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.77 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_dnn_model(input_shape):
  59.     model = tf.keras.Sequential([
  60.         tf.keras.layers.Dense(128, activation='relu', input_shape=(input_shape,)),
  61.         tf.keras.layers.Dense(64, activation='relu'),
  62.         tf.keras.layers.Dense(1, activation='sigmoid')
  63.     ])
  64.     model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
  65.     return model
  66.  
  67. new_persons_results = [
  68.     [0.030391238492519845, 0.23021081913032299, 0.4743575198860915, 0.639395348276238],
  69.     [0.19790381537769108, 0.37639843860181527, 0.5676528538456297, 0.716530820399044],
  70.     [0.0035245462826666075, 0.23127629815305784, 0.4802171123709532, 0.6591272725083992],
  71.     [0.059230621364548486, 0.24424510845680134, 0.442553808602372, 0.6891856336835676],
  72.     [0.05536813173866345, 0.2538888869331579, 0.47861285542743165, 0.6200559751500355],
  73.     [0.1300359168058454, 0.38443677757577344, 0.5957238735056223, 0.795823160451845],
  74.     [0.1743368240338569, 0.3713129035302336, 0.5640350202165867, 0.7213527928848786],
  75.     [0.09173335232875372, 0.2559096689549753, 0.49527436563146954, 0.6970388573439903],
  76.     [0.015235204378572087, 0.2284904031445293, 0.46613902406934005, 0.6917336579549159],
  77.     [0.0011416656054787145, 0.24567669307188245, 0.4388400949432476, 0.667323193441009],
  78.     [0.11776711, 0.17521301, 0.5074825, 0.8509191],
  79.     [0.12314088, 0.27565651, 0.52214202, 0.77386896],
  80. ]
  81.  
  82.  
  83. new_persons_results =[[1000],
  84. [2000],
  85. [3000],
  86. [4000],
  87. [5000],
  88. [6000],
  89. [7000],
  90. [8000],
  91. [9000],
  92. [10000],
  93. [11000],
  94. [12000],
  95. [13000],
  96. [14000],
  97. [15000],
  98. [16000],
  99. [17000],
  100. [18000],
  101. [19000],
  102. [20000],
  103. [21000],
  104. [22000],
  105. [23000],
  106. [24000],
  107. [25000],
  108. ]
  109.  
  110. uploaded = files.upload()
  111. for filename in uploaded.keys():
  112.     original_path = f"/content/{filename}"
  113.     destination_path = os.path.join("/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'
  118. with open(file_path, 'r') as file:
  119.     code = file.read()
  120.  
  121. A_list = ast.literal_eval(code)
  122. A = np.array(A_list)
  123.  
  124. labels = [results[-1] for results in A]
  125. data = [results[:-1] for results in A]
  126.  
  127. num_training_rows = 10
  128. num_testing_rows = 25
  129.  
  130. X_train, X_test, y_train, y_test = data[:num_training_rows], data[:num_testing_rows], labels[:num_training_rows], labels[:num_testing_rows]
  131.  
  132. mean_values = np.mean(X_train, axis=0)
  133. std_values = np.std(X_train, axis=0)
  134. X_train_normalized = (X_train - mean_values) / std_values
  135. X_test_normalized = (X_test - mean_values) / std_values
  136.  
  137. # Verify normalization
  138. print("Mean of X_train_normalized (should be close to 0):", np.mean(X_train_normalized, axis=0))
  139. print("Std of X_train_normalized (should be close to 1):", np.std(X_train_normalized, axis=0))
  140.  
  141. # Generate images from normalized data for CNN
  142. image_training = create_imageN(X_train_normalized, y_train, label_colors)
  143. image_testing = create_imageN(X_test_normalized, y_test, label_colors_testing)
  144.  
  145. # Resize images to a fixed size for CNN input
  146. image_training_resized = [resize(img[:, :-1], (100, 100, 3)) for img in image_training]
  147. image_testing_resized = [resize(img[:, :-1], (100, 100, 3)) for img in image_testing]
  148.  
  149. # Check image shapes
  150. print(f"Shape of image_training_resized[0]: {image_training_resized[0].shape}")
  151. print(f"Shape of image_testing_resized[0]: {image_testing_resized[0].shape}")
  152.  
  153. # Reshape images for CNN
  154. X_train_cnn = np.array(image_training_resized)
  155. X_test_cnn = np.array(image_testing_resized)
  156.  
  157. mean_train_cnn = np.mean(X_train_cnn, axis=(0, 1, 2))
  158. std_train_cnn = np.std(X_train_cnn, axis=(0, 1, 2))
  159. X_train_cnn_normalized = (X_train_cnn - mean_train_cnn) / std_train_cnn
  160. X_test_cnn_normalized = (X_test_cnn - mean_train_cnn) / std_train_cnn
  161.  
  162. # DNN Model
  163. dnn_model = create_dnn_model(len(X_train[0]))
  164.  
  165. # Training DNN Model
  166. dnn_accuracy_history = []
  167. epochs = 200
  168.  
  169. for epoch in tqdm_notebook(range(epochs)):
  170.     history_dnn = dnn_model.fit(X_train_normalized, np.array(y_train), epochs=1, verbose=0, shuffle=False)
  171.     dnn_accuracy_history.append(history_dnn.history['accuracy'][0])
  172.  
  173.     if epoch == 1:
  174.         y_pred_after_2nd_epoch_dnn = dnn_model.predict(X_test_normalized)
  175.         y_pred_binary_after_2nd_epoch_dnn = [1 if pred >= 0.5 else 0 for pred in y_pred_after_2nd_epoch_dnn]
  176.         image_testing_before_2nd_epoch_dnn = create_image(X_test_normalized, y_pred_binary_after_2nd_epoch_dnn, label_colors_testing)
  177.  
  178.     if epoch >= epochs - 1:
  179.         print(f"HERE HERE Epoch: {epoch}, Epochs: {epochs}\n")
  180.  
  181.         # Iterate through new persons
  182.         for idx, personNEW_results in enumerate(new_persons_results, start=1):
  183.             assert len(personNEW_results) == len(X_train[0]), "Mismatch in the number of features."
  184.             personNEW_results_normalized = (np.array(personNEW_results) - mean_values) / std_values
  185.             personNEW_prediction_dnn = dnn_model.predict(np.array([personNEW_results_normalized]))
  186.             personNEW_label_dnn = 1 if personNEW_prediction_dnn >= 0.5 else 0
  187.             y_pred_after_50_epochs_dnn = dnn_model.predict(X_test_normalized)
  188.             y_pred_binary_after_50_epochs_dnn = [1 if pred >= 0.5 else 0 for pred in y_pred_after_50_epochs_dnn]
  189.             image_testing_after_50_epochs_dnn = create_image(X_test_normalized, y_pred_binary_after_50_epochs_dnn, label_colors_testing)
  190.             image_personNEW_dnn = create_imageN([personNEW_results_normalized], [personNEW_label_dnn], label_colors)
  191.             plt.figure(figsize=(5, 5))
  192.             plt.imshow(image_personNEW_dnn)
  193.             plt.title(f"New Person {idx} - DNN\nLabel: {personNEW_label_dnn}, Prediction: {personNEW_prediction_dnn}")
  194.             plt.axis("off")
  195.             plt.show()
  196.  
  197. # CNN Model
  198. cnn_model = create_cnn_model((100, 100, 3))
  199. np.set_printoptions(threshold=np.inf)
  200.  
  201. # Training CNN Model
  202. cnn_accuracy_history = []
  203.  
  204. for epoch in tqdm_notebook(range(epochs)):
  205.     history_cnn = cnn_model.fit(X_train_cnn_normalized, np.array(y_train), epochs=1, verbose=0, shuffle=False)
  206.     cnn_accuracy_history.append(history_cnn.history['accuracy'][0])
  207.  
  208.     if epoch == 1:
  209.         y_pred_after_2nd_epoch_cnn = cnn_model.predict(X_test_cnn_normalized)
  210.         y_pred_binary_after_2nd_epoch_cnn = [1 if pred >= 0.5 else 0 for pred in y_pred_after_2nd_epoch_cnn]
  211.         image_testing_before_2nd_epoch_cnn = create_image(X_test_normalized, y_pred_binary_after_2nd_epoch_cnn, label_colors_testing)
  212.  
  213.     if epoch >= epochs - 1:
  214.         print(f"HERE HERE Epoch: {epoch}, Epochs: {epochs}\n")
  215.  
  216.         # Iterate through new persons
  217.         for idx, personNEW_results in enumerate(new_persons_results, start=1):
  218.             assert len(personNEW_results) == len(X_train[0]), "Mismatch in the number of features."
  219.            
  220.             # Check the new person's data before normalization
  221.             print(f"Person {idx} original results: {personNEW_results}")
  222.            
  223.             personNEW_results_normalized = (np.array(personNEW_results) - mean_values) / std_values
  224.             print(f"Person {idx} normalized results: {personNEW_results_normalized}")
  225.            
  226.             image_personNEW = create_imageN([personNEW_results_normalized], [0], label_colors)
  227.             image_personNEW_resized = resize(image_personNEW[:, :-1], (100, 100, 3))
  228.             image_personNEW_resized_normalized = (image_personNEW_resized - mean_train_cnn) / std_train_cnn  # Normalize new person image
  229.            
  230.             # Check the resized and normalized image
  231.             print(f"Person {idx} resized and normalized image shape: {image_personNEW_resized_normalized.shape}")
  232.             print(f"Person {idx} resized and normalized image: {image_personNEW_resized_normalized}")
  233.            
  234.             personNEW_prediction_cnn = cnn_model.predict(np.array([image_personNEW_resized_normalized]))
  235.             print(f"Person {idx} prediction: {personNEW_prediction_cnn}")
  236.            
  237.             personNEW_label_cnn = 1 if personNEW_prediction_cnn >= 0.5 else 0
  238.             y_pred_after_epochs_cnn = cnn_model.predict(X_test_cnn_normalized)
  239.             y_pred_binary_after_epochs_cnn = [1 if pred >= 0.5 else 0 for pred in y_pred_after_epochs_cnn]
  240.             image_testing_after_epochs_cnn = create_image(X_test_normalized, y_pred_binary_after_epochs_cnn, label_colors_testing)
  241.             image_personNEW_cnn = create_imageN([personNEW_results_normalized], [personNEW_label_cnn], label_colors)
  242.             plt.figure(figsize=(5, 5))
  243.             plt.imshow(image_personNEW_cnn)
  244.             plt.title(f"New Person {idx} - CNN\nLabel: {personNEW_label_cnn}, Prediction: {personNEW_prediction_cnn}")
  245.             plt.axis("off")
  246.             plt.show()
  247.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement