当前位置: 首页>>代码示例>>Python>>正文


Python brain.Brain类代码示例

本文整理汇总了Python中brain.Brain的典型用法代码示例。如果您正苦于以下问题:Python Brain类的具体用法?Python Brain怎么用?Python Brain使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Brain类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: Conversation

class Conversation(object):

    def __init__(self, persona, mic, profile):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)

    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)
        while True:
            self._logger.debug("Started listening for keyword '%s'",
                               self.persona)
            threshold, transcribed = self.mic.passiveListen(self.persona)
            self._logger.debug("Stopped listening for keyword '%s'",
                               self.persona)

            if not transcribed or not threshold:
                self._logger.info("Nothing has been said or transcribed.")
                continue
            self._logger.info("Keyword '%s' has been said!", self.persona)

            self._logger.debug("Started to listen actively with threshold: %r",
                               threshold)
            input = self.mic.activeListenToAllOptions(threshold)
            self._logger.debug("Stopped to listen actively with threshold: %r",
                               threshold)

            if input:
                self.brain.query(input)
开发者ID:tdmike,项目名称:SASCHA,代码行数:35,代码来源:conversation.py

示例2: test_saves_event_if_event_is_not_already_stored

 def test_saves_event_if_event_is_not_already_stored(self):
     Brain.create(self.event)
     stored_event = Brain.read("223-unique-id")
     assert stored_event.title == "Cool event"
     assert stored_event.notification_sent == False
     assert str(stored_event.date) == str(self.event.date)
     assert str(stored_event.enrollment_date) == str(self.event.enrollment_date)
开发者ID:michaelmcmillan,项目名称:BedpresBro,代码行数:7,代码来源:brain_test.py

示例3: Conversation

class Conversation(object):

    def __init__(self, persona, speaker, profile):
        self.persona = persona
        self.speaker = speaker
        self.profile = profile
        self.notifier = Notifier(profile)
        self.brain = Brain(speaker, profile)

    def handleForever(self):

        while True:

            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                self.speaker.say(notif)

            threshold, transcribed = self.speaker.passiveListen(self.persona)
            if not threshold or not transcribed:
                continue

            input = self.speaker.activeListenToAllOptions(threshold)

            if input:
                self.brain.query(self.profile, transcribed)
开发者ID:saarthaks,项目名称:just-another-AI,代码行数:25,代码来源:conversation.py

示例4: Conversation

class Conversation(object):

    def __init__(self, persona, mic, profile, dispatcherClient):
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile, dispatcherClient)
        
    def delegateInput(self, text):
        """A wrapper for querying brain."""
        self.brain.query(text)

    def handleForever(self):
        """Delegates user input to the handling function when activated."""
        while True:

            # # Print notifications until empty
            # notifications = self.notifier.getAllNotifications()
            # for notif in notifications:
            #     self.mic.say(notif)

            threshold, transcribed = self.mic.passiveListen(self.persona)
            if not transcribed or not threshold:
                continue

            input = self.mic.activeListen(threshold)
            if input:
                self.delegateInput(input)
            else:
                self.mic.say("Pardon?")
开发者ID:easyNav,项目名称:easyNav-Voice-deprecated-,代码行数:30,代码来源:conversation.py

示例5: compare_iteration

def compare_iteration(model_prefix, iterations, diversities, training_text, seed_sentence=None):
    result = {}
    index = 0
    for requested_iteration in iterations:
        for file_name in [x for x in os.listdir(data_path('')) if x.startswith(model_prefix)]:
            try:
                (runid, maxlen, step, lstm_size, rest) = file_name.split('-')
                (dropout, iteration, rest) = rest.split('_')
                if str(iteration) != str(requested_iteration):
                    continue
                (maxlen, step, lstm_size, dropout) = (int(maxlen), int(step), int(lstm_size), float(dropout))
                brain = Brain(maxlen=maxlen, lstm_size=lstm_size, dropout=dropout,
                              training_text=training_text)
                seed_sentence = seed_sentence or brain.random_seed_sentence()
                print 'sentence: ' + seed_sentence
                print '---- loading model: ' + file_name
                model = brain.load_model_with_prefix(file_name)

                length = 340

                for diversity in diversities:
                    generated = brain.generate_full(
                        model=model,
                        n=length,
                        diversity=diversity,
                        seed_sentence=seed_sentence)
                    result[(index, file_name, diversity)] = generated
                    index += 1
                    print generated
            except:
                print "Unexpected error with {}: {}".format(file_name, sys.exc_info()[1])
                raise

        for (ix, name, div), generated in sorted(result.iteritems()):
            print "ix={}, model={}, div={}| {}".format(ix, name, div, generated.encode('utf-8'))
开发者ID:gregaw,项目名称:ml,代码行数:35,代码来源:tweeterator.py

示例6: RelayToIRC

class RelayToIRC(irc.IRCClient):
    """
    Wire bot brain, job queue, and config into a Twisted IRC client
    """
    timestamp = None

    def connectionMade(self):
        self.config = self.factory.config
        self.nickname = self.config["irc"]["nick"]
        self.realname = self.config["irc"]["realname"]
        self.channel = self.config["irc"]["channel"]
        if "maxlen" in self.config["irc"]:
            text.maxlen = self.config["irc"]["maxlen"]

        self.sourceURL = self.config["source_url"]

        irc.IRCClient.connectionMade(self)

        if "pass" in self.config["irc"]:
            if "ownermail" in self.config["irc"]:
                self.msg("NickServ", "REGISTER %s %s" % (self.config["irc"]["pass"], self.config["irc"]["ownermail"]))
            elif "regverify" in self.config["irc"]:
                self.msg("NickServ", "VERIFY REGISTER %s %s" % (self.config["irc"]["nick"], self.config["irc"]["regverify"]))
            self.msg("NickServ", "IDENTIFY %s" % self.config["irc"]["pass"])

    def signedOn(self):
        self.join(self.channel)

    def joined(self, channel):
        print "Joined channel %s as %s" % (channel, self.nickname)
        self.brain = Brain(self.config, sink=self)
        #XXX get outta here:
        source = JobQueue(
            definition=self.config["jobs"],
            sink=self,
            interval=self.config["poll_interval"]
        )
        source.run()

    def privmsg(self, user, channel, message):
        if message.find(self.nickname) >= 0:
            self.brain.respond(user, message)

    def write(self, data):
        if isinstance(data, list):
            for line in data:
                self.write(line)
            return
        self.say(self.channel, data.encode('ascii', 'replace'))
        self.timestamp = datetime.datetime.utcnow()


    @staticmethod
    def run(config):
        factory = ReconnectingClientFactory()
        factory.protocol = RelayToIRC
        factory.config = config
        reactor.connectTCP(config["irc"]["host"], config["irc"]["port"], factory)
        reactor.run()
开发者ID:adamwight,项目名称:slander,代码行数:59,代码来源:irc.py

示例7: setUp

 def setUp(self):
     Brain.connection = sqlite3.connect(":memory:")
     Brain.setup()
     self.event = MagicMock(
         id="223-unique-id",
         title="Cool event",
         enrollment_date=datetime.now(),
         date=datetime.now(),
         notification_sent=False,
     )
开发者ID:michaelmcmillan,项目名称:BedpresBro,代码行数:10,代码来源:brain_test.py

示例8: train_single_player

def train_single_player():
  sim = DummyGame() # Breakout()
  brain = Brain(sim.width, sim.height, sim.actions_count)
  player = QLearn(sim, brain, "AI")
  scorer = Scorer(stats_frequency)

  for games in xrange(train_games):
    play_single_player_game(player, sim, scorer, display_board=True)
  # Save the model to disk and load it as an inference only model
  model_path = brain.save(models_root)
  print 'Saved trained model to', model_path
开发者ID:andrei-alpha,项目名称:deep-qlearning,代码行数:11,代码来源:main.py

示例9: Conversation

class Conversation(object):

    def __init__(self, persona, mic, profile, isPassiveEnabled):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)
        self.isPassiveEnabled = isPassiveEnabled

    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)
        while True:
            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                self._logger.info("Received notification: '%s'", str(notif))

            self._logger.debug("Started listening for keyword '%s'",
                               self.persona)
            threshold, transcribed, passivePhrases = \
                self.mic.passiveListen(self.persona)
            self._logger.debug("Stopped listening for keyword '%s'",
                               self.persona)

            if not transcribed or not threshold:
                self._logger.info("Nothing has been said or transcribed.")
                continue

            self._logger.info("Keyword '%s' has been said!", self.persona)

            if self.isPassiveEnabled is True and len(passivePhrases) != 0:

                input = passivePhrases
                self._logger.debug("Checking for passive phrase '%s' with " +
                                   "threshold: %r", input, threshold)

            else:

                self._logger.debug("Started to listen actively with " +
                                   "threshold: %r", threshold)
                input = self.mic.activeListenToAllOptions(threshold)
                self._logger.debug("Stopped to listen actively with " +
                                   "threshold: %r", threshold)

            if input:
                self.brain.query(input)
            else:
                self.mic.say("Pardon?")
开发者ID:PLockhart,项目名称:jasper-client,代码行数:54,代码来源:conversation.py

示例10: train_with_opponent

def train_with_opponent():
  sim = Connect4()
  if train_mode == "mixt":
    opponents = [RandomPlayer("Rand")]
    for idx, model_path in enumerate(os.listdir(models_root)):
      full_path = os.path.join(models_root, model_path)
      prev_brain = Brain(sim.width,
                         sim.height,
                         sim.actions_count,
                         load_path=full_path)
      opponents.append(QLearn(sim, prev_brain, "v" + str(idx)))
  elif train_mode == "random":
    opponents = [RandomPlayer("Rand")]
  elif train_mode == "minmax":
    opponents = [MinMax(max_level=minmax_level)]
  else:
    raise ValueError, ("Invalid train_mode. Got %s expected "
      "(mixt|random|minmax)") % train_mode

  scorer = Scorer(stats_frequency)
  for step in xrange(new_models):
    brain = Brain(sim.width, sim.height, sim.actions_count)
    player = QLearn(sim, brain, "AI")

    w = [0.1 * i for i in xrange(1, len(opponents) + 1)]
    p = [wi / sum(w) for wi in w]

    for games in xrange(1, 100000):
      if games % win_threshold_games == 0:
        # If the new model wins more than 90% of the games of the last 300
        win_statistics = scorer.get_statistics(win_threshold_games)[0]
        if win_statistics > win_threshold_percentage:
          # Save the model to disk and load it as an inference only model
          model_path = brain.save(models_root)
          prev_brain = Brain(sim.width,
                             sim.height,
                             sim.actions_count,
                             load_path=model_path)
          opponents.append(QLearn(sim, prev_brain, "V" + str(step),
                                  exploration_period=0, discount_factor=0.9))
          print "-" * 70
          print("New model wins %d%s against previous models after "
                "%d games") % (win_statistics, "%", games)
          print "-" * 70
          print ''
          break

      opponent = np.random.choice(opponents, 1, p)[0]
      players = [player, opponent]
      play_game_with_opponent(players, sim, scorer)

  human_player = HumanPlayer("Player")
  while True:
    play_game_with_opponent([opponents[-1], human_player], sim, scorer)
开发者ID:andrei-alpha,项目名称:deep-qlearning,代码行数:54,代码来源:main.py

示例11: input

def input():
	actionflg=True
	inputs=config.get('if').keys()
	for input in inputs:
		logger.debug(input)
		brain=Brain(config)
		brain.action(input)
		if not brain.outflag:
			actionflg=False
			break
	if actionflg:
		action()
开发者ID:sramakr,项目名称:rengine,代码行数:12,代码来源:rule.py

示例12: Conversation

class Conversation(object):

    def __init__(self, persona, mic, profile, house):
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile, house)
        self.notifier = Notifier(profile, house)
        self.house = house

    def delegateInput(self, text):
        """A wrapper for querying brain."""

        # check if input is meant to start the music module
        if any(x in text.upper() for x in ["SPOTIFY", "MUSIC"]):
            # check if mpd client is running
            try:
                client = MPDClient()
                client.timeout = None
                client.idletimeout = None
                client.connect("localhost", 6600)
            except:
                self.mic.say(
                    "I'm sorry. It seems that Spotify is not enabled. Please read the documentation to learn how to configure Spotify.")
                return

            self.mic.say("Please give me a moment, I'm loading your Spotify playlists.")
            music_mode = MusicMode(self.persona, self.mic)
            music_mode.handleForever()
            return

        self.brain.query(text)

    def handleForever(self):
        """Delegates user input to the handling function when activated."""
        while True:

            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                print notif
                self.mic.say(notif)
            try:
                threshold, transcribed = self.mic.passiveListen(self.persona)
            except:
                continue

            if threshold:
                input = self.mic.activeListen(threshold)
                if input:
                    self.delegateInput(input)
                else:
                    self.mic.say("Pardon?")
开发者ID:pyroesque,项目名称:jasper_home_automation,代码行数:53,代码来源:conversation.py

示例13: train

def train(maxlens, steps, dropouts, dataset):
    for code, text_file in dataset:
        for maxlen in maxlens:
            for step in steps:
                for dropout in dropouts:
                    print '=========== TRAINING on: maxlen={}, step={}, lstm_size=128, dropout={}, text={}'.format(
                        maxlen,
                        step,
                        dropout,
                        text_file)
                    brain = Brain(maxlen=maxlen, lstm_size=128, dropout=dropout,
                                  training_text=text_file)
                    brain.train(runid='11,{},tweets'.format(code), iterations=7, step=step)
开发者ID:gregaw,项目名称:ml,代码行数:13,代码来源:tweeterator.py

示例14: Conversation

class Conversation(object):

    def __init__(self, persona, mic, profile):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)

    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)
        while on == True:

            nu()
            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                self._logger.info("Received notification: '%s'", str(notif))

            self._logger.debug("Started listening for keyword '%s'",
                               self.persona)
            threshold, transcribed = self.mic.passiveListen(self.persona)
            self._logger.debug("Stopped listening for keyword '%s'",
                               self.persona)

            if not transcribed or not threshold:
                self._logger.info("Nothing has been said or transcribed.")
                continue
            self._logger.info("Keyword '%s' has been said!", self.persona)

            self._logger.debug("Started to listen actively with threshold: %r",
                               threshold)
            input = self.mic.activeListenToAllOptions(threshold)
            self._logger.debug("Stopped to listen actively with threshold: %r",
                               threshold)

            if input:
                self.brain.query(input)
            else:
                messages = ["what?",
                            "what did you say",
                            "Say that again?", "speak the fuck up", "i cant fucking hear you", "blah blah blah", "did you say something?"]

                message = random.choice(messages)
                zip2()
                self.mic.say(message)
开发者ID:DarthToker,项目名称:jasper-client,代码行数:51,代码来源:conversationbac.py

示例15: Conversation

class Conversation(object):

    def __init__(self, persona, mic, profile):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)

    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)
        while True:
            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                self._logger.info("Received notification: '%s'", str(notif))

            # Word we listen for to self terminate
            TERMINATE = 'GOODBYE'

            self._logger.debug("Started listening for keyword '%s' or '%s'",
                               self.persona, TERMINATE)
            threshold, transcribed = self.mic.passiveListen(self.persona, TERMINATE)
            self._logger.debug("Stopped listening for keyword '%s' or '%s'",
                               self.persona, TERMINATE)

            if not transcribed or not threshold:
                self._logger.info("Nothing has been said or transcribed.")
                continue
            self._logger.info("Keyword '%s' has been said!", self.persona)

            # Terminate on goodbye
            if transcribed == TERMINATE:
                friendly.goodbye(self.mic, self.profile)
                sys.exit(0)

            self._logger.debug("Started to listen actively with threshold: %r",
                               threshold)
            input = self.mic.activeListenToAllOptions(threshold)
            self._logger.debug("Stopped to listen actively with threshold: %r",
                               threshold)

            if input:
                self.brain.query(input)
            else:
                self.mic.say("Pardon?")
开发者ID:shaggy8871,项目名称:jasper,代码行数:51,代码来源:conversation.py


注:本文中的brain.Brain类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。