2

this function has 3 modes, i.e. 'hh' 'ih' and 'ho'.

    def mutate_add_connection(self, mode = 'hh'):
        if mode == 'hh':    # hidden --> hidden
            node_a = random.choice(self.hidden_nodes_dict.values())
            node_b = random.choice(self.hidden_nodes_dict.values())
            self.connect_node_pair(node_a,node_b, 'sort')
        elif mode == 'ih':  # input --> hidden
            node_a = random.choice(self.input_nodes_dict.values())
            node_b = random.choice(self.hidden_nodes_dict.values())
            node_b.set_links((node_a,random.choice([-1, 1])))
        elif mode == 'ho':  # hidden --> output
            node_b.set_links((node_a,random.choice([-1, 1])))
            node_a = random.choice(self.hidden_nodes_dict.values())
            node_b = random.choice(self.output_nodes_dict.values())

In practice of adding-connection mutate, I need to use these 3 modes with a probability. Let't say 33.33% for each mode.

So I am planning to add a mode 'auto' in this function. In order to call the 3 mode above "randomly".

    def mutate_add_connection(self, mode = 'hh'):
        if mode == 'auto':
            chosen_mode = random.choice(['hh','ih','ho'])
            self.mutate_add_connection(mode=chosen_mode)
        # the code above .......

But I am not sure if it is a good idea. Could you suggest a better way to achieve my propose? Thanks~

zheyuanWang
  • 1,158
  • 2
  • 16
  • 30

1 Answers1

6

While there are often good uses for recursive functions, it's not really needed here. Just reassign the mode argument.

    def mutate_add_connection(self, mode = 'hh'):
        if mode == 'auto':
            mode = random.choice(['hh','ih','ho'])
        # the code above .......
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • great, thank you for such a clean code. But what if the probabilities to choose them are different?( Let's say, 10.5%, 50.5% and 39%) – zheyuanWang Sep 12 '19 at 08:55
  • 1
    See https://stackoverflow.com/questions/3679694/a-weighted-version-of-random-choice – Barmar Sep 12 '19 at 19:25
  • How you choose the auto mode is independent of how you execute the rest of the code using it. – Barmar Sep 12 '19 at 19:26