Okonar

ШІ

Oct 16th, 2023 (edited)
9
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.45 KB | None | 0 0
  1. import tensorflow as tf
  2. from tensorflow.keras.models import Sequential
  3. from tensorflow.keras.layers import Dense
  4. import maze
  5. import maze_collection as mc
  6. import random as r
  7. import numpy as np
  8. import matplotlib.pyplot as plt
  9.  
  10. def build_neural_network(num_memory_units):
  11.     model = Sequential()
  12.     model.add(Dense(6, activation='sigmoid', input_shape=(2 + num_memory_units,)))
  13.     model.add(Dense(6, activation='sigmoid'))
  14.     model.add(Dense(4 + num_memory_units, activation='linear'))
  15.  
  16.     left_output = model.layers[-1].output[:, :4]
  17.     right_output = model.layers[-1].output[:, 4:]
  18.  
  19.     y = tf.nn.softmax(left_output)
  20.     memory_units = tf.sigmoid(right_output)
  21.  
  22.     return model, y, memory_units
  23.  
  24. def main(output_file_name):
  25.     # housekeeping
  26.     m = maze.Maze(mc.simple_maze)
  27.     learning_rate = 0.0001
  28.     num_memory_units = 0
  29.     graphical = True
  30.     file_output = True
  31.  
  32.     if file_output is True:
  33.         # output to file (this is set to overwrite!)
  34.         file = open(output_file_name + ".txt", "w")
  35.         file.write("Iter\tWon?\tSteps\tAll steps\n")
  36.  
  37.     # neural network structure
  38.     model, y, memory_units = build_neural_network(num_memory_units)
  39.  
  40.     weights_list = model.trainable_variables
  41.  
  42.     # training setup
  43.     maxSteps = 4
  44.     iteration = 0
  45.     maxIterations = 10000
  46.  
  47.     steps_taken = np.zeros(maxIterations)
  48.  
  49.     # Plot display -----------------------------------------------------------------------------------------------------
  50.     if graphical is True:
  51.         spread = 50
  52.  
  53.         plt.ion()
  54.         fig = plt.figure("Maze solver")
  55.         ax = fig.add_subplot(111)
  56.         ax.axis([0, maxIterations/spread + 1, 0, maxSteps + 1])
  57.         plt.ylabel("Steps taken")
  58.         plt.xlabel("Iterations ({})".format(spread))
  59.         ax.plot([0], [0])
  60.         ax.grid()
  61.  
  62.         iterations = []
  63.         duration_history = []
  64.  
  65.     # Looping through iterations
  66.     while iteration < maxIterations:
  67.         # Current step
  68.         step = 0
  69.  
  70.         # All outputs and dp_dthetas for this iteration
  71.         probabilities = np.zeros(maxSteps)
  72.         dp_dthetas = list()
  73.  
  74.         memory = np.zeros(num_memory_units)
  75.  
  76.         movements = ""
  77.  
  78.         while m.won is False and step < maxSteps:
  79.             # Defining neural network input
  80.             input_values = np.array([m.normal_x(), m.normal_y()])
  81.             input_values = np.append(input_values, memory)
  82.  
  83.             # Running input through the neural network
  84.             [output, dp_dtheta, output_memory] = model.predict(np.array([input_values]))
  85.  
  86.             # Random value between 0 and 1, inclusive on both sides
  87.             result = r.uniform(0, 1)
  88.  
  89.             if result <= output[0][0]:
  90.                 # Up
  91.                 m.move_up()
  92.                 probabilities[step] = output[0][0]
  93.                 dp_dthetas.append(dp_dtheta)
  94.                 movements += "U"
  95.             elif result <= output[0][0] + output[0][1]:
  96.                 # Right
  97.                 m.move_right()
  98.                 probabilities[step] = output[0][1]
  99.                 dp_dthetas.append(dp_dtheta)
  100.                 movements += "R"
  101.             elif result <= output[0][0] + output[0][1] + output[0][2]:
  102.                 # Down
  103.                 m.move_down()
  104.                 probabilities[step] = output[0][2]
  105.                 dp_dthetas.append(dp_dtheta)
  106.                 movements += "D"
  107.             elif result <= output[0][0] + output[0][1] + output[0][2] + output[0][3]:
  108.                 # Left
  109.                 m.move_left()
  110.                 probabilities[step] = output[0][3]
  111.                 dp_dthetas.append(dp_dtheta)
  112.                 movements += "L"
  113.  
  114.             memory = output_memory[0]
  115.             step += 1
  116.  
  117.         print("Iteration #{:05d}\tWon: {}\tSteps taken: {:04d}\tSteps: {}".format(iteration, m.won,
  118.                                                                                   step, movements))
  119.         if file_output is True:
  120.             file.write("{:05d}\t{}\t{:04d}\t{}\n".format(iteration, m.won, step, movements))
  121.  
  122.         # Assigning a reward
  123.         # reward = maxSteps - (2 * step)  # linear reward function
  124.         reward = maxSteps - pow(step, 2)  # power reward function
  125.  
  126.         # Applying weight change for every step taken, based on the reward given at the end
  127.         for i in range(step):
  128.             deltaTheta = [(learning_rate * (1 / probabilities[i]) * reward) * dp_dthetas[i][j]
  129.                           for j in range(len(weights_list)]
  130.             ]
  131.             model.train_on_batch(np.array([input_values]), deltaTheta)
  132.  
  133.         steps_taken[iteration] = step
  134.         if graphical is True and iteration % spread == 0:
  135.             steps_mean = np.mean(steps_taken[iteration-spread:iteration+1])
  136.             iterations = iterations+[iteration/spread]
  137.             duration_history = duration_history+[steps_mean]
  138.             del ax.lines[0]
  139.             ax.plot(iterations, duration_history, 'b-', label='Traj1')
  140.             plt.draw()
  141.             plt.pause(0.001)
  142.  
  143.         m.reset()
  144.  
  145.         iteration += 1
  146.     if file_output is True:
  147.         file.close()
  148.     if graphical is True:
  149.         if file_output is True:
  150.             plt.savefig(output_file_name + ".png")
  151.         else:
  152.             plt.show()
  153.         #input("Press [enter] to continue.")
  154.         plt.close()
  155.  
  156. if __name__ == "__main__":
  157.     for run in range(10, 15):
  158.         number = "{:05d}".format(run)
  159.         main("./output/one_step_fixed-no_memory/" + number)
  160.  
Advertisement
Add Comment
Please, Sign In to add comment