Advertisement
here2share

# tk_ReLu_With_Matrix_Test.py

Jun 15th, 2024
470
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.91 KB | None | 0 0
  1. # tk_ReLu_With_Matrix_Test.py ZZZ unable to make this "learn"
  2.  
  3. import tkinter as tk
  4. import random
  5. import math
  6. import string
  7.  
  8. ww = 1200
  9. hh = 600
  10.  
  11. root = tk.Tk()
  12. root.title("tk ReLu With Matrix Test")
  13. root.geometry(f"{ww}x{hh}+10+10")
  14.  
  15. scrollbar = tk.Scrollbar(root)
  16. scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
  17.  
  18. canvas = tk.Canvas(root, width=ww, height=hh, bg="black", yscrollcommand=scrollbar.set)
  19. canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
  20.  
  21. scrollbar.config(command=canvas.yview)
  22.  
  23. def dot(a, b):
  24.     return [[sum(x * y for x, y in zip(row, col)) for col in zip(*b)] for row in a]
  25.  
  26. def transpose(matrix):
  27.     return list(zip(*matrix))
  28.  
  29. def leaky_relu(matrix):
  30.     return [[max(0.01 * x, x) for x in row] for row in matrix]
  31.  
  32. def square_diff(matrix1, matrix2):
  33.     return sum((x - y) ** 2 for row1, row2 in zip(matrix1, matrix2) for x, y in zip(row1, row2))
  34.  
  35. def create_random_matrix(rows, cols):
  36.     return [[random.uniform(-1, 1) for _ in range(cols)] for _ in range(rows)]
  37.  
  38. def backpropagation(x, y):
  39.     global grad_w2, grad_w1
  40.     h = dot(x, w1)
  41.     h_relu = leaky_relu(h)
  42.     y_pred = dot(h_relu, w2)
  43.     grad_y_pred = [[2 * (yp - yt) for yp, yt in zip(yp_row, yt_row)] for yp_row, yt_row in zip(y_pred, y)]
  44.     grad_w2 = dot(transpose(h_relu), grad_y_pred)
  45.     grad_h_relu = dot(grad_y_pred, transpose(w2))
  46.     grad_h = [[ghr if h_val > 0 else 0.01 * ghr for ghr, h_val in zip(ghr_row, h_row)] for ghr_row, h_row in zip(grad_h_relu, h)]
  47.     grad_w1 = dot(transpose(x), grad_h)
  48.  
  49. def compute_gain(x, y):
  50.     global h_relu, h, y_pred, gain
  51.     h = dot(x, w1)
  52.     h_relu = leaky_relu(h)
  53.     y_pred = dot(h_relu, w2)
  54.     gain = square_diff(y_pred, y)
  55.     gain_col.append(gain)
  56.  
  57. encode_factor = 1 / 62
  58. encode_index = dict((s, ((i + 1) * encode_factor)) for (i, s) in enumerate(string.digits + string.ascii_letters))
  59. def encode_input(data):
  60.     encoded = []
  61.     for char in data:
  62.         encoded.append(encode_index[char])
  63.     return encoded
  64.  
  65. def softmax(x):
  66.     max_val = max(x)
  67.     exps = [math.exp(val - max_val) for val in x]
  68.     sum_exps = sum(exps)
  69.     return [exp / sum_exps for exp in exps]
  70.  
  71. def euclidean_distance(v1, v2):
  72.     return math.sqrt(sum((a - b) ** 2 for a, b in zip(v1, v2)))
  73.  
  74. def predict(data):
  75.     encoded_data = encode_input(data)
  76.     x = [encoded_data]
  77.     h = dot(x, w1)
  78.     h_relu = leaky_relu(h)
  79.     y_pred = dot(h_relu, w2)[0]
  80.  
  81.     normalized_predictions = softmax(y_pred)
  82.  
  83.     min_distance = float('inf')
  84.     nearest_category = None
  85.  
  86.     distances = []
  87.     for category in range(1, 6):
  88.         target_vector = all_target_weights[category]
  89.         distance = euclidean_distance(normalized_predictions, target_vector)
  90.         distances += [(100 - distance, category)]
  91.         if distance < min_distance:
  92.             min_distance = distance
  93.             nearest_category = category
  94.  
  95.     prediction = nearest_category
  96.  
  97.     confidence = max(normalized_predictions)
  98.  
  99.     return prediction, confidence, distances
  100.  
  101. N, D_in, H, D_out = 10, 25, 12, 5  # Adjusted D_out for 5 categories
  102. w1 = create_random_matrix(D_in, H)
  103. w2 = create_random_matrix(H, D_out)
  104. learning_rate = 0.002
  105. gain_col = []
  106. w1_changes = [[0 for _ in range(H)] for _ in range(D_in)]
  107. w2_changes = [[0 for _ in range(D_out)] for _ in range(H)]
  108.  
  109. j = 255 / 400
  110. a = [int(i * j) for i in range(400)]
  111. b = [0 for _ in range(300)]
  112. red = a[::-1] + b + b
  113. green = b + b + a
  114. blue = b + a + b
  115. get_color = [f'#{r:02X}{g:02X}{b:02X}' for r, g, b in zip(red, green, blue)]
  116.  
  117. def get_color_from_weight(weight, target_weight):
  118.     diff = abs(weight - target_weight)
  119.     diff = 1 - max(0, min(1, diff))
  120.     return get_color[int(diff * 999)]
  121.  
  122. # Training Data
  123. def shuffle_mixed_case(s):
  124.     mixed = [c.lower() if random.random() < 0.5 else c.upper() for c in s]
  125.     random.shuffle(mixed)
  126.     return ''.join(mixed)
  127.  
  128. def category_1():
  129.     digits = ''.join(random.choices(string.digits, k=7))
  130.     combined = digits + 'yellow'
  131.     combined += ''.join(random.choices(string.ascii_letters, k=(25 - len(combined))))
  132.     return shuffle_mixed_case(combined)
  133.  
  134. def category_2():
  135.     digits = ''.join(random.choices(string.digits, k=9))
  136.     combined = digits + 'helloworld'
  137.     combined += ''.join(random.choices(string.ascii_letters, k=(25 - len(combined))))
  138.     return shuffle_mixed_case(combined)
  139.  
  140. def category_3():
  141.     combined = 'python3407'
  142.     combined += ''.join(random.choices(string.ascii_letters + string.digits, k=(25 - len(combined))))
  143.     return shuffle_mixed_case(combined)
  144.  
  145. def category_4():
  146.     combined = 'thankyou12345'
  147.     combined += ''.join(random.choices(string.ascii_letters + string.digits, k=(25 - len(combined))))
  148.     return shuffle_mixed_case(combined)
  149.  
  150. def category_5():
  151.     s = []
  152.     for i in range(12):
  153.         s.append(random.choice(string.ascii_letters))
  154.         s.append(random.choice(string.digits))
  155.     s.append(random.choice(string.ascii_letters))
  156.     return ''.join(s)
  157.  
  158. def generate_training_data(category=None):
  159.     if category not in (1, 2, 3, 4, 5):
  160.         category = random.randint(1, 5)
  161.     if category == 1:
  162.         return category_1()
  163.     elif category == 2:
  164.         return category_2()
  165.     elif category == 3:
  166.         return category_3()
  167.     elif category == 4:
  168.         return category_4()
  169.     elif category == 5:
  170.         return category_5()
  171.  
  172. def update_canvas(i):
  173.     cell_width = 20
  174.     cell_height = 20
  175.     num_cols = 25
  176.  
  177.     encoded_data = encode_input(data)
  178.  
  179.     target_weights = [all_target_weights[correct_category][N] for N in range(25)]
  180.  
  181.     for j, char in enumerate(data):
  182.         color_value = get_color_from_weight(encoded_data[j], target_weights[j])
  183.         x0 = j * cell_width
  184.         y0 = i * cell_height
  185.         x1 = x0 + cell_width
  186.         y1 = y0 + cell_height
  187.         canvas.create_rectangle(x0, y0, x1, y1, fill=color_value, outline="gray")
  188.         canvas.create_text(x0 + 10, y0 + 10, text=char, fill="white")
  189.  
  190.     is_correct = prediction == correct_category
  191.     result_text = f"Y [{correct_category}] " if is_correct else f"N [{correct_category}] "
  192.     progress.append(100 if is_correct else 0)
  193.     progress.pop(0)
  194.     gain = sum(progress) / 500
  195.     gain_text = f"{gain:.2f}% gain"
  196.     canvas.create_text(num_cols * cell_width + 30, i * cell_height + 10, text=result_text, fill="white", anchor=tk.W)
  197.     canvas.create_text(num_cols * cell_width + 80, i * cell_height + 10, text=gain_text, fill="white", anchor=tk.W)
  198.     k = 2
  199.     for distance, idx in distances:
  200.         canvas.create_text(num_cols * cell_width + (95 * k), i * cell_height + 10, text=f"{idx}: {distance:.5f}%", fill="white", anchor=tk.W)
  201.         k += 1
  202.  
  203.     canvas.config(scrollregion=(0, 0, ww, (i + 1) * cell_height + cell_height))
  204.  
  205.     root.update()
  206.  
  207. number_of_data = 5000
  208. categories = [1, 2, 3, 4, 5] * (number_of_data // 5)
  209. random.shuffle(categories)
  210.  
  211. training_data = [(generate_training_data(category), category) for category in categories]
  212. training_inputs = [encode_input(data[0]) for data in training_data]
  213. training_labels = [[1 if i + 1 == data[1] else 0 for i in range(D_out)] for data in training_data]
  214. progress = [0 for i in range(500)]
  215.  
  216. all_target_weights = {
  217.     1: [0.6 for _ in range(25)],
  218.     2: [0.3 for _ in range(25)],
  219.     3: [0.00 for _ in range(25)],
  220.     4: [-0.3 for _ in range(25)],
  221.     5: [-0.6 for _ in range(25)]
  222. }
  223.  
  224. batch_size = 30
  225. num_batches = len(categories) // batch_size
  226.  
  227. # Training loop
  228. line = 0
  229. for epoch in range(100):  # Number of epochs
  230.     for batch in range(num_batches):
  231.         x_batch = training_inputs[batch * batch_size:(batch + 1) * batch_size]
  232.         y_batch = training_labels[batch * batch_size:(batch + 1) * batch_size]
  233.  
  234.         compute_gain(x_batch, y_batch)
  235.         backpropagation(x_batch, y_batch)
  236.  
  237.         for i in range(batch_size):
  238.             data, correct_category = training_data[batch * batch_size + i]
  239.             prediction, confidence, distances = predict(data)
  240.             update_canvas(line)
  241.             line += 1
  242.             for n in range(25):
  243.                 all_target_weights[correct_category][n] += learning_rate * (training_labels[batch * batch_size + i][correct_category - 1] - sum(w1[n]))
  244.  
  245.         for i in range(D_in):
  246.             for j in range(H):
  247.                 w1[i][j] -= learning_rate * grad_w1[i][j]
  248.                 w1_changes[i][j] += learning_rate * grad_w1[i][j]
  249.         for i in range(H):
  250.             for j in range(D_out):
  251.                 w2[i][j] -= learning_rate * grad_w2[i][j]
  252.                 w2_changes[i][j] += learning_rate * grad_w2[i][j]
  253.  
  254. root.mainloop()
  255.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement