def __init__(self): print("Init") if self.instance is not None: raise ValueError( "looks like you forgot to call getbot function ? ") self.stemmer = LancasterStemmer() data = pickle.load(open(paths.getPath('trained_data'), "rb")) self.words = data['words'] self.classes = data['classes'] train_x = data['train_x'] train_y = data['train_y'] with open(paths.getJsonPath()) as json_data: self.intents = json.load(json_data) net = tflearn.input_data(shape=[None, len(train_x[0])]) net = tflearn.fully_connected(net, 8) net = tflearn.fully_connected(net, 8) net = tflearn.fully_connected(net, len(train_y[0]), activation='softmax') net = tflearn.regression(net) self.model = tflearn.DNN(net, tensorboard_dir=paths.getPath('train_logs')) self.model.load(paths.getPath('model.tflearn'))
def saveGoals( self, fileName='goals.txt' ): '''Saves the goals to the specified file. @param fileName The name to write the goals to. ''' Goals.DIGITS = 2 path = paths.getPath( fileName, False ) print "Writing goals to:", path f = open( path, 'w' ) f.write ('''<?xml version="1.0"?> <Population > ''') for gs in self.goalEditor: node = gs.xmlElement() if ( node ): node.writexml( f, indent=' ', addindent=' ', newl='\n' ) f.write( '\n</Population>' ) f.close()
def handleKey(event, context, view, theGraph, obstacles, agents, field): global editState result = ContextResult() if (context): result = context.handleKeyboard(event, view) if (result.isHandled()): return result mods = pygame.key.get_mods() hasShift = mods & pygame.KMOD_SHIFT hasCtrl = mods & pygame.KMOD_CTRL hasAlt = mods & pygame.KMOD_ALT if (event.type == pygame.KEYDOWN): if (event.key == pygame.K_p): print theGraph elif (event.key == pygame.K_s and hasCtrl): if (editState == GRAPH_EDIT): fileName = paths.getPath('graph.txt', False) f = open(fileName, 'w') f.write('%s\n' % theGraph.newAscii()) f.close() print "Graph saved!", fileName elif (event.key == pygame.K_e): editState = (editState + 1) % EDIT_STATE_COUNT result.setNeedsRedraw(True) elif (event.key == pygame.K_DELETE): if (editState == GRAPH_EDIT): if (theGraph.fromID != None): theGraph.deleteVertex(theGraph.fromID) theGraph.fromID = None result.setNeedsRedraw(True) elif (theGraph.activeEdge != None): theGraph.deleteEdge(theGraph.activeEdge) theGraph.activeEdge = None result.setNeedsRedraw(True) elif (hasAlt and event.key == pygame.K_F4): raise Exception return result
def main(): import optparse parser = optparse.OptionParser() parser.add_option("-r", "--roadmap", help="Optional roadmap file to load", action="store", dest="roadmapName", default='') parser.add_option("-g", "--goals", help="Optional goal definition file to load", action="store", dest="goalsName", default='') parser.add_option("-b", "--obstacle", help="Optional obstacle file to load.", action="store", dest='obstName', default='') parser.add_option("-a", "--agent", help="Optional agent position file to load.", action="store", dest='agtName', default='') parser.add_option("-f", "--field", help="Optional vector field file to load.", action="store", dest='fieldName', default='') parser.add_option( "-c", "--createField", help= 'Creates a field based on the domain of the obstacles - ignored if --field(-f) is specified', action='store_true', dest='createField', default=False) parser.add_option("-s", "--scb", help="Optional scb file to load.", action="store", dest='scbName', default='') parser.add_option( "-i", "--inDir", help= "Optional directory to find input files - only applied to file names with relative paths", action="store", dest='inDir', default='.') parser.add_option( "-o", "--outDir", help= "Optional directory to write output files - only applied to file names with relative paths", action="store", dest='outDir', default='.') parser.add_option( '--region', help= 'Specify the bounding region of the action. If provided, it will set the initial camera properties. Format is minX minY maxX maxY', nargs=4, type='float', dest='boundRegion', default=None) options, args = parser.parse_args() paths.setInDir(options.inDir) paths.setOutDir(options.outDir) obstName = paths.getPath(options.obstName) agtName = paths.getPath(options.agtName) roadmapName = paths.getPath(options.roadmapName) fieldName = paths.getPath(options.fieldName) scbName = paths.getPath(options.scbName) goalsName = paths.getPath(options.goalsName) print "Arguments:" print "\tInput dir: ", options.inDir print "\tOutput dir:", options.outDir print "\tobstacles: ", obstName print "\tagents: ", agtName print "\troad map: ", roadmapName print "\tfield: ", fieldName print "\tscbName: ", scbName print "\tGoals: ", goalsName if (obstName): obstacles, bb = readObstacles(obstName) else: obstacles = ObstacleSet() bb = AABB() if (not options.boundRegion is None): bb.min = Vector3(options.boundRegion[0], options.boundRegion[1], 0) bb.max = Vector3(options.boundRegion[2], options.boundRegion[3], 0) print bb else: bb.min = Vector3(-100, -100, 0) bb.max = Vector3(100, 100, 0) agents = AgentSet(0.23) if (agtName): agents.initFromFile(agtName) if (scbName != ''): # This reads the agent radius from the file, but no longer visualizes the agents # This is a bit of a hack. It would be better to simply disable drawing the # agents when the scb playback context is active. But I don't have the time # to figure out an elegant solution to this. agents.clear() if (fieldName): field = GLVectorField((0, 0), (1, 1), 1) field.read(fieldName) elif (options.createField): print "Instantiate vector field from geometry:", bb bbSize = bb.max - bb.min field = GLVectorField((bb.min.x, bb.min.y), (bbSize.y, bbSize.x), 2.0) else: field = None graph = Graph() if (roadmapName): graph.initFromFile(roadmapName) # create viewer pygame.init() fontname = pygame.font.get_default_font() font = pygame.font.Font(fontname, 12) w = bb.max.x - bb.min.x h = bb.max.y - bb.min.y view = View((w, h), (bb.min.x, bb.min.y), (w, h), (bb.min.x, bb.min.y), (800, 600), font) view.HELP_TEXT = 'View controls:' + \ '\n\tpan - Ctrl + left mouse button' + \ '\n\tzoom in - mouse wheel up' + \ '\n\tzoom out - mouse wheel down' + \ '\n\tzoom - Shift + left mouse button (up and down)' view.initWindow('Create roadmap') pygame.key.set_repeat(250, 10) view.initGL() if (field): field.newGLContext() ## field = None # load goals if (goalsName): try: goalSets = Goals.readGoals(goalsName) except ValueError as e: print "Error parsing goals:", str(e) print "\tUsing empty GoalSet" goalSets = [Goals.GoalSet()] else: goalSets = [Goals.GoalSet()] goalVis = GoalEditor(goalSets) context = ContextSwitcher() context.addContext(PositionContext(), pygame.K_q) context.addContext(GoalContext(goalVis), pygame.K_g) context.addContext(AgentContext(agents), pygame.K_a) context.addContext(ObstacleContext(obstacles), pygame.K_o) if (field): context.addContext(FieldEditContext(field), pygame.K_f) if (scbName != ''): context.addContext(SCBContext(scbName, obstacles, agents.defRadius), pygame.K_s) context.newGLContext() redraw = True running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False break elif (event.type == pygame.MOUSEMOTION or event.type == pygame.MOUSEBUTTONUP or event.type == pygame.MOUSEBUTTONDOWN): result = handleMouse(event, context, view, graph, obstacles, agents, field) redraw |= result.needsRedraw() elif (event.type == pygame.KEYDOWN or event.type == pygame.KEYUP): try: result = handleKey(event, context, view, graph, obstacles, agents, field) redraw |= result.needsRedraw() except Exception as e: print "Error with keyboard event" print "\t", e running = False elif (event.type == pygame.VIDEORESIZE): view.resizeGL(event.size) if (field): field.newGLContext() context.newGLContext() redraw |= True elif (event.type == pygame.VIDEOEXPOSE): redraw |= True if (redraw): drawGL(view, context, obstacles, graph, agents, field, goalVis) message(view, updateMsg(agents.count())) pygame.display.flip() if (context): name = context.exportDisplay() if (name): pygame.image.save(view.surface, name) redraw = False writeRoadmap()
training.append([bag, output_row]) random.shuffle(training) training = np.array(training) train_x = list(training[:, 0]) train_y = list(training[:, 1]) tf.reset_default_graph() net = tflearn.input_data(shape=[None, len(train_x[0])]) net = tflearn.fully_connected(net, 8) net = tflearn.fully_connected(net, 8) net = tflearn.fully_connected(net, len(train_y[0]), activation='softmax') net = tflearn.regression(net) model = tflearn.DNN(net, tensorboard_dir=paths.getPath('train_logs')) model.fit(train_x, train_y, n_epoch=20000, batch_size=500, show_metric=True) model.save(paths.getPath('model.tflearn')) def clean_up_sentence(sentence): sentence_words = nltk.word_tokenize(sentence) sentence_words = [stemmer.stem(word.lower()) for word in sentence_words] return sentence_words def bow(sentence, words, show_details=False): sentence_words = clean_up_sentence(sentence) bag = [0] * len(words) for s in sentence_words: for i, w in enumerate(words):