def __init__(self, db, learner_no): self.dummy = 0 self.db = db self.w = Weights(len(db) - 1) self.number_learners = learner_no self.learners = [] self.learner_priority = []
def compare_weights(weights_x, weights_o): # initialize variables row = 15 col = 15 x_labels = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'o', 'p' ] y_labels = [ '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15' ] pattern = Pattern() # set up the starting conditions game_continue = True current_player = player_1 current_board_state = create_board(row, col) # play game weights = Weights() while game_continue: current_board_state, current_player = alternate_moves( current_board_state, current_player, x_labels, weights_x, weights_o) isWin, winner = found_winner(pattern, current_board_state) if isWin: game_continue = False return current_board_state, winner
def setup(self): # constants rho = 1026.0 #kg/m^3 g = 9.81 #m/s^2 indeps = self.add_subsystem('indeps', om.IndepVarComp()) indeps.add_output('Cb', 0.45) #unitless indeps.add_output('L', 30) #meters indeps.add_output('D', 4) #meters indeps.add_output('T', 2) #meters indeps.add_output('B', 6) #meters indeps.add_output('S', 400) #meters^2 indeps.add_output('MCR', 500) #kilowatts # setting velocity to be constant, as the optimization can only occur at one speed #indeps.add_output('Vk', 16) #knots cycle = self.add_subsystem('cycle', om.Group()) cycle.add_subsystem('resist', Resistance()) cycle.add_subsystem('wts', Weights()) cycle.connect('wts.Wt', 'resist.Delta') #cycle.nonlinear_solver = om.NonlinearBlockGS() # define the component whose output will be constrained self.add_subsystem('const', om.ExecComp('Fn = 8.23/((9.81*L)**(0.5))')) #connect components self.connect('indeps.Cb', ['cycle.resist.Cb', 'cycle.wts.Cb']) self.connect('indeps.L', ['cycle.resist.L', 'cycle.wts.L']) self.connect('indeps.D', 'cycle.wts.D') self.connect('indeps.T', 'cycle.wts.T') self.connect('indeps.B', 'cycle.wts.B') self.connect('indeps.S', 'cycle.resist.S')
def main(): # initialize variables row = 15 col = 15 x_labels = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'o', 'p' ] y_labels = [ '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15' ] pattern = Pattern() # set up the starting conditions game_continue = True running = True current_player = player_1 # TODO - first player chosen randomly current_board_state = create_board(row, col) # play game weights = Weights() pygame.init() screen = pygame.display.set_mode((490, 490)) pygame.display.set_caption("Gomoku") icon = pygame.image.load('assets/gomoku.png') pygame.display.set_icon(icon) while running: clicked = False got_input = False for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.MOUSEBUTTONDOWN and game_continue: got_input = get_input_pos(event.pos, current_board_state, 'x') clicked = True update_board(screen, current_board_state) pygame.display.update() game_continue = not check_win(pattern, current_board_state, screen) if game_continue: update_board(screen, current_board_state) pygame.display.update() if clicked and got_input: font = pygame.font.SysFont('arial', 15) text = font.render('Waiting for Computer Move', True, (0, 0, 0)) textRect = text.get_rect() screen.blit(text, textRect) textRect.center = (300, 300) pygame.event.set_blocked(pygame.MOUSEBUTTONDOWN) pygame.display.update() current_board_state, _ = alternate_moves( current_board_state, 'o', x_labels, weights, weights) update_board(screen, current_board_state) pygame.display.update() pygame.event.set_allowed(None) game_continue = not check_win(pattern, current_board_state, screen)
def create_sampleList(self, sample_freq, db, sum_w8): sample = [] #sample.append([]) #sample.append([]) rand_list = [uniform(0, 1) for x in range(sample_freq)] #print(rand_list) w = Weights(100) for r in rand_list: #print(r) i = w.index_sum_weight(sum_w8, r) #print(i) sample.append(db[i]) #sample[1] = sample[1] + [i] header = db[0] sample = [header] + sample return sample
def brain_init(parent_brains): brains = [] for _ in range(parent_brains): w = Weights() w.w_1 = np.random.randint(8, 12) w.w_2 = np.random.randint(15, 20) w.w_3 = np.random.randint(0, 10) w.w_4 = np.random.randint(10, 15) w.w_5 = np.random.randint(0, 5) w.w_6 = np.random.randint(0, 5) brains.append(w) return brains
def __init__(self, n_Hlayer, n_node, alpha, activation): self.n_Hlayer = n_Hlayer self.n_node = n_node n_node_in = 784 self.n_node_out = 10 self.val_acc = 0 self.alpha = alpha self.activation = activation self.Net = [Layer(0, n_node_in, self.activation)] self.WR = [] for layer in range(1, n_Hlayer + 1): self.Net.append(Layer(layer, self.n_node, self.activation)) if self.activation == 'sigmoid': self.Net.append( Layer(n_Hlayer + 1, self.n_node_out, self.activation)) elif self.activation == 'relu': self.Net.append(Layer(n_Hlayer + 1, self.n_node_out, 'softmax')) for layer_ind in range(n_Hlayer + 1): self.WR.append( Weights(self.Net[layer_ind], self.Net[layer_ind + 1]))
def dijkstra(graph, src, dest, nodes_count): """ Implementation of Dikstra algorithm """ unexplored = graph.copy() # Add the entire graph as unexplored shortest_distances = {} # Store shortest distances from two nodes predecessor = {} # Store visited nodes for back-tracking min_heap = MinHeap(nodes_count) # Min Heap weights_handler = Weights(graph) graph = weights_handler.get_weights() # Update weights # Initialize shortest path of every node as INFINITY for node in unexplored: shortest_distances[node] = math.inf if node != src: min_heap.add(shortest_distances[node], node) # Save node's shortest distance in the min heap shortest_distances[src] = 0 # Source has '0' length min_heap.add(shortest_distances[src], src) # Save source's shortest distance in the min heap # Running the loop while all the nodes have been visited while unexplored: node_to_visit = None # The node we should visit next node_to_visit = min_heap.get_node_min( ) # Get shortest current distance # Explore all neighbors for child_node, value in unexplored[node_to_visit].items(): # Check if the new path is the shortest discovered yet if value + shortest_distances[node_to_visit] < shortest_distances[ child_node]: shortest_distances[child_node] = value + shortest_distances[ node_to_visit] # Replace the new shortest path min_heap.update(child_node, shortest_distances[child_node]) predecessor[ child_node] = node_to_visit # Store the node for backtracking unexplored.pop( node_to_visit ) # Node is visited & removed from the 'unexplored' list min_heap.pop() # Remove the minimum value from heap # Get the shortest path using backtracking shortest_path = back_track(src, dest, predecessor) # Check if the target has actually been visited if shortest_distances[dest] != math.inf: # print("Shortest Distance:\t", str(shortest_distances[dest])) # Print shortest distance from source to the destination print("Shortest Path:\t\t", " -> ".join(shortest_path)) # Print the shortest path # print("Shortest Distances:\t", str(shortest_distances)) # Print the detailed path print("ETA:\t\t\t", "{:.3f}".format(get_travel_time(graph, shortest_path)), "Minutes") # Prints the ETA weights_handler.update_traffic(shortest_path) # Update the traffic draw(graph, shortest_path) # Draw plot
class Adaboost: db = [] learners = [] learner_priority = [] number_learners = 0 sample_limit = 20 def __init__(self, db, learner_no): self.dummy = 0 self.db = db self.w = Weights(len(db) - 1) self.number_learners = learner_no self.learners = [] self.learner_priority = [] def createSample(self): sum_w8 = self.w.sum_weights(self.w.weights) #print(sum_w8) rd = ReadCSV() sample = rd.create_sampleList(self.sample_limit, self.db, sum_w8) return sample def create_learner(self, sample): s = Stump(sample) s.tree() #s.print_decision() self.learners.append(s) def determine_error(self, index_learner): rr = 0 db_ = self.db dec_values = [] pred_values = [] for j in range(1, len(db_)): temp = self.db[j] # print("val of data ",temp) tval = self.learners[index_learner].decide_for_test(temp) # print(tval) pred_values.append(tval) actual_dec = temp[20] dec_values.append(actual_dec) if tval != actual_dec: rr += self.w.weights[j - 1] return rr, dec_values, pred_values def modify_weights(self, dec_val, pred_val, rr): db_ = self.db for j in range(1, len(db_)): if pred_val[j - 1] == dec_val[j - 1]: self.w.weights[j - 1] *= rr def updatePriority(self, rr): self.w.normalize() # print(w.weights) rr = 1 / rr rr = math.log(rr, 2) #print(rr) self.learner_priority.append(rr) def algo(self): for i in range(self.number_learners): #print("learner no ",k) #print(self.w.weights) sample = self.createSample() #for r in sample: # print(r) self.create_learner(sample) rr, dec_val, pred_val = self.determine_error(i) #print(rr) #print(len(dec_val)) rr = rr / (1 - rr) self.modify_weights(dec_val, pred_val, rr) self.updatePriority(rr) return self.learners, self.learner_priority
from Weights import Weights from Stability import Stability import openmdao.api as om import math # build the model, defining units in the process` prob = om.Problem() indeps = prob.model.add_subsystem('indeps', om.IndepVarComp()) #define independent variables (to be explored) indeps.add_output('Cb', 0.31) #unitless indeps.add_output('T', 2, units='m') #meters indeps.add_output('L', 20, units='m') #meters indeps.add_output('B', 5, units='m') #meters # add the weights component previously defined in Weights.py prob.model.add_subsystem('wts', Weights()) # add the stability component from Stability.py prob.model.add_subsystem('stab', Stability()) # define component whose output will be constrained # units defined, excess represents the 'excess' displacement of the design prob.model.add_subsystem( 'const', om.ExecComp('Disp=Cb*T*L*B', Disp={'units': 't'}, T={'units': 'm'}, L={'units': 'm'}, B={'units': 'm'})) #connect components prob.model.connect('indeps.Cb', ['wts.Cb', 'stab.Cb', 'const.Cb'])