Advertisement
max2201111

display image fractal like range(5)

Jun 26th, 2024
534
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 16.47 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. import sys
  14.  
  15. display(Javascript('IPython.OutputArea.auto_scroll_threshold = 9999;'))
  16.  
  17. label_colors = {0: [0, 128, 0], 1: [255, 0, 0]}
  18. label_colors_testing = {0: [0, 128, 0], 1: [255, 0, 0]}
  19.  
  20. %matplotlib inline
  21.  
  22. def create_image(data, predictions, label_colors, column_min_vals, column_max_vals):
  23.     num_rows, num_columns = len(data), len(data[0])
  24.     image = np.zeros((num_rows, num_columns + 1, 3), dtype=np.uint8)
  25.     for i in range(num_rows):
  26.         for j in range(num_columns):
  27.             pixel_value = int(np.interp(data[i][j], [column_min_vals[j], column_max_vals[j]], [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, column_min_vals, column_max_vals):
  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], [column_min_vals[j], column_max_vals[j]], [0, 255]))
  39.             image_training[i, j] = np.array([pixel_value] * 3)
  40.         image_training[i, -1] = label_colors[int(predictions[i])]
  41.     return image_training
  42.  
  43. def create_cnn_model(input_shape):
  44.     model = tf.keras.Sequential([
  45.         tf.keras.layers.InputLayer(input_shape=input_shape),
  46.         tf.keras.layers.Conv2D(filters=32, kernel_size=(3, 3), activation='relu'),
  47.         tf.keras.layers.MaxPooling2D(pool_size=(2, 2)),
  48.         tf.keras.layers.Dropout(0.25),
  49.         tf.keras.layers.Flatten(),
  50.         tf.keras.layers.Dense(64, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.001)),
  51.         tf.keras.layers.Dropout(0.5),
  52.         tf.keras.layers.Dense(1, activation='sigmoid')
  53.     ])
  54.     model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
  55.     return model
  56.  
  57. new_persons_results = [
  58.     [0.030391238492519845, 0.23021081913032299, 0.4743575198860915, 0.639395348276238],
  59.     [0.19790381537769108, 0.37639843860181527, 0.5676528538456297, 0.716530820399044],
  60.     [0.0035245462826666075, 0.23127629815305784, 0.4802171123709532, 0.6591272725083992],
  61.     [0.059230621364548486, 0.24424510845680134, 0.442553808602372, 0.6891856336835676],
  62.     [0.05536813173866345, 0.2538888869331579, 0.47861285542743165, 0.6200559751500355],
  63.     [0.1300359168058454, 0.38443677757577344, 0.5957238735056223, 0.795823160451845],
  64.     [0.1743368240338569, 0.3713129035302336, 0.5640350202165867, 0.7213527928848786],
  65.     [0.09173335232875372, 0.2559096689549753, 0.49527436563146954, 0.6970388573439903],
  66.     [0.015235204378572087, 0.2284904031445293, 0.46613902406934005, 0.6917336579549159],
  67.     [0.0011416656054787145, 0.24567669307188245, 0.4388400949432476, 0.667323193441009],
  68.     [0.11776711, 0.17521301, 0.5074825,  0.8509191 ],
  69.     [0.12314088, 0.27565651, 0.52214202, 0.77386896],
  70. ]
  71.  
  72. uploaded = files.upload()
  73. for filename in uploaded.keys():
  74.     original_path = f"/content/{filename}"
  75.     destination_path = os.path.join("/content/", "/content/DATA2")
  76.     shutil.move(original_path, destination_path)
  77.     print(f"Soubor {filename} byl přesunut do {destination_path}")
  78.  
  79. file_path = '/content/DATA2'
  80. with open(file_path, 'r') as file:
  81.     code = file.read()
  82.  
  83. A_list = ast.literal_eval(code)
  84. A = np.array(A_list)
  85.  
  86. labels = [results[-1] for results in A]
  87. data = [results[:-1] for results in A]
  88.  
  89. num_training_rows = 50
  90. num_testing_rows = 50
  91. 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]
  92. X_train, X_test, y_train, y_test = data[:num_training_rows], data[:num_testing_rows], labels[:num_training_rows], labels[:num_testing_rows]
  93.  
  94. mean_values = np.mean(X_train, axis=0)
  95. std_values = np.std(X_train, axis=0)
  96. X_train_normalized = (X_train - mean_values) / std_values
  97. X_test_normalized = (X_test - mean_values) / std_values
  98.  
  99. column_min_vals = np.min(X_train_normalized, axis=0)
  100. column_max_vals = np.max(X_train_normalized, axis=0)
  101.  
  102. # Verify normalization
  103. print("Mean of X_train_normalized (should be close to 0):", np.mean(X_train_normalized, axis=0))
  104. print("Std of X_train_normalized (should be close to 1):", np.std(X_train_normalized, axis=0))
  105.  
  106. dnn_model = tf.keras.Sequential([
  107.     tf.keras.layers.Dense(128, activation='relu', input_shape=(len(X_train[0]),)),
  108.     tf.keras.layers.BatchNormalization(),
  109.     tf.keras.layers.Dropout(0.2),  # Snížení dropout rate
  110.     tf.keras.layers.Dense(64, activation='relu'),
  111.     tf.keras.layers.BatchNormalization(),
  112.     tf.keras.layers.Dropout(0.2),
  113.     tf.keras.layers.Dense(32, activation='relu'),
  114.     tf.keras.layers.BatchNormalization(),
  115.     tf.keras.layers.Dropout(0.2),
  116.     tf.keras.layers.Dense(16, activation='relu'),
  117.     tf.keras.layers.BatchNormalization(),
  118.     tf.keras.layers.Dropout(0.2),
  119.     tf.keras.layers.Dense(1, activation='sigmoid')
  120. ])
  121. dnn_model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.001), loss='binary_crossentropy', metrics=['accuracy'])
  122.  
  123. # Generování dummy předpovědí pro tréninková data
  124. train_predictions = [0] * len(X_train_normalized)  # Dummy předpovědi pro tréninkové obrázky
  125.  
  126. # Generování skutečných předpovědí pro testovací data
  127. test_predictions = (dnn_model.predict(X_test_normalized) > 0.5).astype(int).flatten()
  128.  
  129. # Generování obrázků z normalizovaných dat
  130. image_training = create_imageN(X_train_normalized, y_train, label_colors, column_min_vals, column_max_vals)
  131. image_testing = create_image(X_test_normalized, test_predictions, label_colors_testing, column_min_vals, column_max_vals)
  132.  
  133. # Ověření počtu vygenerovaných obrázků
  134. print("Počet tréninkových obrázků:", len(image_training))
  135. print("Počet testovacích obrázků:", len(image_testing))
  136. assert len(image_training) == 50, "Počet tréninkových obrázků by měl být 50."
  137. assert len(image_testing) == len(X_test_normalized), "Počet testovacích obrázků by měl odpovídat počtu testovacích vzorků."
  138.  
  139. # Změna velikosti obrázků na pevnou velikost pro vstup do CNN
  140. image_training_resized = [resize(img[:, :-1], (100, 100, 3)) for img in image_training]
  141. image_testing_resized = [resize(img[:, :-1], (100, 100, 3)) for img in image_testing]
  142.  
  143. # Ověření změny velikosti obrázků
  144. print("Tvar prvního tréninkového obrázku po změně velikosti:", image_training_resized[0].shape)
  145. print("Tvar prvního testovacího obrázku po změně velikosti:", image_testing_resized[0].shape)
  146.  
  147. # Převod obrázků do formátu numpy pole
  148. X_train_cnn = np.array(image_training_resized)
  149. X_test_cnn = np.array(image_testing_resized)
  150.  
  151. # Ověření tvaru polí
  152. print("Tvar X_train_cnn:", X_train_cnn.shape)
  153. print("Tvar X_test_cnn:", X_test_cnn.shape)
  154. assert X_train_cnn.shape == (50, 100, 100, 3), "Tvar X_train_cnn by měl být (50, 100, 100, 3)."
  155.  
  156. # Funkce pro zobrazení obrázku
  157. def display_image(image, title="Image"):
  158.     plt.imshow(image)
  159.     plt.title(title)
  160.     plt.axis('off')
  161.     plt.show()
  162.  
  163. # Zobrazení několika tréninkových obrázků
  164. for i in range(5):
  165.     display_image(X_train_cnn[i], title=f"Tréninkový obrázek {i+1}")
  166.  
  167. # Trénování modelu DNN
  168. dnn_accuracy_history = []
  169. epochs = 500  # Reduced to 500 for quicker convergence
  170.  
  171. for epoch in tqdm_notebook(range(epochs)):
  172.     history_dnn = dnn_model.fit(X_train_normalized, np.array(y_train), epochs=1, verbose=0, shuffle=False)
  173.     dnn_accuracy_history.append(history_dnn.history['accuracy'][0])
  174.  
  175.     if epoch == 1:
  176.         y_pred_after_2nd_epoch_dnn = dnn_model.predict(X_test_normalized)
  177.         y_pred_binary_after_2nd_epoch_dnn = [1 if pred >= 0.5 else 0 for pred in y_pred_after_2nd_epoch_dnn]
  178.         image_testing_before_2nd_epoch_dnn = create_image(X_test_normalized, y_pred_binary_after_2nd_epoch_dnn, label_colors_testing, column_min_vals, column_max_vals)
  179.  
  180.     if epoch >= epochs-1:
  181.         print(f"HERE HERE Epoch: {epoch}, Epochs: {epochs}\n")
  182.         sys.stdout.flush()
  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.             personNEW_prediction_dnn = dnn_model.predict(np.array([personNEW_results_normalized]))
  189.             personNEW_label_dnn = 1 if personNEW_prediction_dnn >= 0.5 else 0
  190.             y_pred_after_50_epochs_dnn = dnn_model.predict(X_test_normalized)
  191.             y_pred_binary_after_50_epochs_dnn = [1 if pred >= 0.5 else 0 for pred in y_pred_after_50_epochs_dnn]
  192.             image_testing_after_50_epochs_dnn = create_image(X_test_normalized, y_pred_binary_after_50_epochs_dnn, label_colors_testing, column_min_vals, column_max_vals)
  193.             image_personNEW_dnn = create_imageN([personNEW_results_normalized], [personNEW_label_dnn], label_colors, column_min_vals, column_max_vals)
  194.             plt.figure(figsize=(5, 5))
  195.             plt.imshow(image_personNEW_dnn)
  196.             plt.title(f"New Person {idx} - DNN\nLabel: {personNEW_label_dnn}, Prediction: {personNEW_prediction_dnn}")
  197.             plt.axis("off")
  198.             plt.show()
  199.  
  200. # CNN Model
  201. cnn_model = tf.keras.Sequential([
  202.     tf.keras.layers.InputLayer(input_shape=(100, 100, 3)),
  203.     tf.keras.layers.Conv2D(filters=32, kernel_size=(3, 3), activation='relu'),
  204.     tf.keras.layers.MaxPooling2D(pool_size=(2, 2)),
  205.     tf.keras.layers.Dropout(0.25),
  206.     tf.keras.layers.Flatten(),
  207.     tf.keras.layers.Dense(64, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.001)),
  208.     tf.keras.layers.Dropout(0.5),
  209.     tf.keras.layers.Dense(1, activation='sigmoid')
  210. ])
  211. cnn_model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
  212.  
  213. # Training CNN Model
  214. cnn_accuracy_history = []
  215.  
  216. for epoch in tqdm_notebook(range(epochs)):
  217.     history_cnn = cnn_model.fit(X_train_cnn, np.array(y_train), epochs=1, verbose=0, shuffle=False)
  218.     cnn_accuracy_history.append(history_cnn.history['accuracy'][0])
  219.  
  220.     if epoch == 1:
  221.         y_pred_after_2nd_epoch_cnn = cnn_model.predict(X_test_cnn)
  222.         y_pred_binary_after_2nd_epoch_cnn = [1 if pred >= 0.5 else 0 for pred in y_pred_after_2nd_epoch_cnn]
  223.         image_testing_before_2nd_epoch_cnn = create_image(X_test_normalized, y_pred_binary_after_2nd_epoch_cnn, label_colors_testing, column_min_vals, column_max_vals)
  224.  
  225.     if epoch >= epochs-1:
  226.         print(f"HERE HERE Epoch: {epoch}, Epochs: {epochs}\n")
  227.         sys.stdout.flush()
  228.  
  229.         # Iterate through new persons
  230.         for idx, personNEW_results in enumerate(new_persons_results, start=1):
  231.             assert len(personNEW_results) == len(X_train[0]), "Mismatch in the number of features."
  232.             personNEW_results_normalized = (np.array(personNEW_results) - mean_values) / std_values
  233.             image_personNEW = create_imageN([personNEW_results_normalized], [0], label_colors, column_min_vals, column_max_vals)
  234.             image_personNEW_resized = resize(image_personNEW[:, :-1], (100, 100, 3))
  235.             personNEW_prediction_cnn = cnn_model.predict(np.array([image_personNEW_resized]))
  236.             personNEW_label_cnn = 1 if personNEW_prediction_cnn >= 0.5 else 0
  237.             y_pred_after_50_epochs_cnn = cnn_model.predict(X_test_cnn)
  238.             y_pred_binary_after_50_epochs_cnn = [1 if pred >= 0.5 else 0 for pred in y_pred_after_50_epochs_cnn]
  239.             image_testing_after_50_epochs_cnn = create_image(X_test_normalized, y_pred_binary_after_50_epochs_cnn, label_colors_testing, column_min_vals, column_max_vals)
  240.             image_personNEW_cnn = create_imageN([personNEW_results_normalized], [personNEW_label_cnn], label_colors, column_min_vals, column_max_vals)
  241.             plt.figure(figsize=(5, 5))
  242.             plt.imshow(image_personNEW_cnn)
  243.             plt.title(f"New Person {idx} - CNN\nLabel: {personNEW_label_cnn}, Prediction: {personNEW_prediction_cnn}")
  244.             plt.axis("off")
  245.             plt.show()
  246.  
  247. # Display the images
  248. plt.figure(figsize=(25, 15))
  249. plt.subplot(2, 2, 1)
  250. plt.imshow(image_training)
  251. plt.title("Training Data")
  252. plt.axis("off")
  253.  
  254. plt.subplot(2, 2, 2)
  255. plt.imshow(image_testing_before_2nd_epoch_dnn)
  256. plt.title("Testing Data (2nd Epoch) - DNN")
  257. plt.axis("off")
  258.  
  259. plt.subplot(2, 2, 3)
  260. plt.imshow(image_testing_after_50_epochs_dnn)
  261. plt.title(f"Testing Data ({epochs} Epochs) - DNN")
  262. plt.axis("off")
  263.  
  264. plt.subplot(2, 2, 4)
  265. plt.imshow(image_personNEW_dnn)
  266. plt.title(f"New Person - DNN\nLabel: {personNEW_label_dnn},[{personNEW_prediction_dnn}]")
  267. plt.axis("off")
  268.  
  269. plt.figure(figsize=(12, 5))
  270. plt.plot(range(1, epochs + 1), dnn_accuracy_history, marker='o')
  271. plt.title('DNN Accuracy Over Epochs')
  272. plt.xlabel('Epochs')
  273. plt.ylabel('Accuracy')
  274. plt.grid()
  275.  
  276. plt.figure(figsize=(25, 15))
  277. plt.subplot(2, 2, 1)
  278. plt.imshow(image_training)
  279. plt.title("Training Data")
  280. plt.axis("off")
  281.  
  282. plt.subplot(2, 2, 2)
  283. plt.imshow(image_testing_before_2nd_epoch_cnn)
  284. plt.title("Testing Data (2nd Epoch) - CNN")
  285. plt.axis("off")
  286.  
  287. plt.subplot(2, 2, 3)
  288. plt.imshow(image_testing_after_50_epochs_cnn)
  289. plt.title(f"Testing Data ({epochs} Epochs) - CNN")
  290. plt.axis("off")
  291.  
  292. plt.subplot(2, 2, 4)
  293. plt.imshow(image_personNEW_cnn)
  294. plt.title(f"New Person - CNN\nLabel: {personNEW_label_cnn},[{personNEW_prediction_cnn}]")
  295. plt.axis("off")
  296.  
  297. plt.figure(figsize=(12, 5))
  298. plt.plot(range(1, epochs + 1), cnn_accuracy_history, marker='o')
  299. plt.title('CNN Accuracy Over Epochs')
  300. plt.xlabel('Epochs')
  301. plt.ylabel('Accuracy')
  302. plt.grid()
  303.  
  304. # Confusion Matrix and Performance Metrics for DNN
  305. dnn_predictions = (dnn_model.predict(X_test_normalized) > 0.5).astype(int)
  306. dnn_conf_matrix = confusion_matrix(y_test, dnn_predictions)
  307. print(f"Confusion Matrix for DNN:\n{dnn_conf_matrix}")
  308. dnn_accuracy = accuracy_score(y_test, dnn_predictions)
  309. dnn_precision = precision_score(y_test, dnn_predictions)
  310. dnn_recall = recall_score(y_test, dnn_predictions)
  311. dnn_f1 = f1_score(y_test, dnn_predictions)
  312. print(f"DNN Accuracy: {dnn_accuracy:.4f}")
  313. print(f"DNN Precision: {dnn_precision:.4f}")
  314. print(f"DNN Recall: {dnn_recall:.4f}")
  315. print(f"DNN F1 Score: {dnn_f1:.4f}")
  316.  
  317. # Confusion Matrix and Performance Metrics for CNN
  318. cnn_predictions = (cnn_model.predict(X_test_cnn) > 0.5).astype(int)
  319. print("PP:",X_test_cnn)
  320. cnn_conf_matrix = confusion_matrix(y_test, cnn_predictions)
  321. print(f"Confusion Matrix for CNN:\n{cnn_conf_matrix}")
  322. cnn_accuracy = accuracy_score(y_test, cnn_predictions)
  323. cnn_precision = precision_score(y_test, cnn_predictions)
  324. cnn_recall = recall_score(y_test, cnn_predictions)
  325. cnn_f1 = f1_score(y_test, cnn_predictions)
  326. print(f"CNN Accuracy: {cnn_accuracy:.4f}")
  327. print(f"CNN Precision: {cnn_precision:.4f}")
  328. print(f"CNN Recall: {cnn_recall:.4f}")
  329. print(f"CNN F1 Score: {cnn_f1:.4f}")
  330.  
  331. # Display confusion matrices
  332. plt.figure(figsize=(12, 5))
  333.  
  334. plt.subplot(1, 2, 1)
  335. sns.heatmap(dnn_conf_matrix, annot=True, fmt='d', cmap='Blues')
  336. plt.xlabel('Predicted')
  337. plt.ylabel('Actual')
  338. plt.title('DNN Confusion Matrix')
  339.  
  340. plt.subplot(1, 2, 2)
  341. sns.heatmap(cnn_conf_matrix, annot=True, fmt='d', cmap='Blues')
  342. plt.xlabel('Predicted')
  343. plt.ylabel('Actual')
  344. plt.title('CNN Confusion Matrix')
  345.  
  346. plt.show()
  347.  
  348. # Optimalizace nového vektoru pro predikci co nejblíže 0.52
  349. target_prediction = 0.52
  350. input_shape = 4
  351. new_vector = np.random.randn(input_shape)
  352. new_vector = tf.Variable(new_vector, dtype=tf.float32)
  353.  
  354. optimizer = tf.optimizers.Adam(learning_rate=0.1)
  355.  
  356. def loss_function():
  357.     prediction = dnn_model(tf.reshape(new_vector, (1, -1)))
  358.     return tf.abs(prediction - target_prediction)
  359.  
  360. # Gradientní sestup
  361. for _ in range(1000):
  362.     optimizer.minimize(loss_function, [new_vector])
  363.  
  364. # Denormalizace výsledného vektoru
  365. result_vector = new_vector.numpy()
  366. denormalized_vector = result_vector * std_values + mean_values
  367. result_prediction = dnn_model.predict(result_vector.reshape(1, -1))
  368.  
  369. print("Výsledný vektor (normalizovaný):", result_vector)
  370. print("Výsledný vektor (denormalizovaný):", denormalized_vector)
  371. print("Predikce výsledného vektoru:", result_prediction)
  372.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement