首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python-整洁的例子坏了

python-整洁的例子坏了
EN

Stack Overflow用户
提问于 2021-04-16 10:03:32
回答 1查看 117关注 0票数 0

我正在尝试运行python neat中的以下代码,它允许您将遗传算法应用于神经网络。这是一个非常有趣的概念,只是我不能让示例代码运行。

代码语言:javascript
复制
"""
2-input XOR example -- this is most likely the simplest possible example.
"""

from __future__ import print_function
import os
import neat
import visualize

# 2-input XOR inputs and expected outputs.
xor_inputs = [(0.0, 0.0), (0.0, 1.0), (1.0, 0.0), (1.0, 1.0)]
xor_outputs = [   (0.0,),     (1.0,),     (1.0,),     (0.0,)]


def eval_genomes(genomes, config):
    for genome_id, genome in genomes:
        genome.fitness = 4.0
        net = neat.nn.FeedForwardNetwork.create(genome, config)
        for xi, xo in zip(xor_inputs, xor_outputs):
            output = net.activate(xi)
            genome.fitness -= (output[0] - xo[0]) ** 2


def run(config_file):
    # Load configuration.
    config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
                         neat.DefaultSpeciesSet, neat.DefaultStagnation,
                         config_file)

    # Create the population, which is the top-level object for a NEAT run.
    p = neat.Population(config)

    # Add a stdout reporter to show progress in the terminal.
    p.add_reporter(neat.StdOutReporter(True))
    stats = neat.StatisticsReporter()
    p.add_reporter(stats)
    p.add_reporter(neat.Checkpointer(5))

    # Run for up to 300 generations.
    winner = p.run(eval_genomes, 300)

    # Display the winning genome.
    print('\nBest genome:\n{!s}'.format(winner))

    # Show output of the most fit genome against training data.
    print('\nOutput:')
    winner_net = neat.nn.FeedForwardNetwork.create(winner, config)
    for xi, xo in zip(xor_inputs, xor_outputs):
        output = winner_net.activate(xi)
        print("input {!r}, expected output {!r}, got {!r}".format(xi, xo, output))

    node_names = {-1:'A', -2: 'B', 0:'A XOR B'}
    visualize.draw_net(config, winner, True, node_names=node_names)
    visualize.plot_stats(stats, ylog=False, view=True)
    visualize.plot_species(stats, view=True)

    p = neat.Checkpointer.restore_checkpoint('neat-checkpoint-4')
    p.run(eval_genomes, 10)


if __name__ == '__main__':
    # Determine path to configuration file. This path manipulation is
    # here so that the script will run successfully regardless of the
    # current working directory.
    local_dir = os.path.dirname(__file__)
    config_path = os.path.join(local_dir, 'config-feedforward')
    run(config_path)

这是配置文件

代码语言:javascript
复制
#--- parameters for the XOR-2 experiment ---#

[NEAT]
fitness_criterion     = max
fitness_threshold     = 3.9
pop_size              = 150
reset_on_extinction   = False

[DefaultGenome]
# node activation options
activation_default      = sigmoid
activation_mutate_rate  = 0.0
activation_options      = sigmoid

# node aggregation options
aggregation_default     = sum
aggregation_mutate_rate = 0.0
aggregation_options     = sum

# node bias options
bias_init_mean          = 0.0
bias_init_stdev         = 1.0
bias_max_value          = 30.0
bias_min_value          = -30.0
bias_mutate_power       = 0.5
bias_mutate_rate        = 0.7
bias_replace_rate       = 0.1

# genome compatibility options
compatibility_disjoint_coefficient = 1.0
compatibility_weight_coefficient   = 0.5

# connection add/remove rates
conn_add_prob           = 0.5
conn_delete_prob        = 0.5

# connection enable options
enabled_default         = True
enabled_mutate_rate     = 0.01

feed_forward            = True
initial_connection      = full

# node add/remove rates
node_add_prob           = 0.2
node_delete_prob        = 0.2

# network parameters
num_hidden              = 0
num_inputs              = 2
num_outputs             = 1

# node response options
response_init_mean      = 1.0
response_init_stdev     = 0.0
response_max_value      = 30.0
response_min_value      = -30.0
response_mutate_power   = 0.0
response_mutate_rate    = 0.0
response_replace_rate   = 0.0

# connection weight options
weight_init_mean        = 0.0
weight_init_stdev       = 1.0
weight_max_value        = 30
weight_min_value        = -30
weight_mutate_power     = 0.5
weight_mutate_rate      = 0.8
weight_replace_rate     = 0.1

[DefaultSpeciesSet]
compatibility_threshold = 3.0

[DefaultStagnation]
species_fitness_func = max
max_stagnation       = 20
species_elitism      = 2

[DefaultReproduction]
elitism            = 2
survival_threshold = 0.2

最后,这是我安装的python-neat版本

代码语言:javascript
复制
pip show neat-python
Name: neat-python
Version: 0.92
Summary: A NEAT (NeuroEvolution of Augmenting Topologies) implementation
Home-page: https://github.com/CodeReclaimers/neat-python 

有没有人可以帮我解决下面的错误?因为到目前为止,我尝试的是从github安装和从pip安装,两者都在示例代码中给出了相同的错误。我也尝试了不同的代码,但我得到了相同的错误。

代码语言:javascript
复制
 ****** Running generation 0 ****** 

Traceback (most recent call last):
  File "driver.py", line 34, in <module>
    winner = p.run(eval_genomes)
  File "/home/j/anaconda3/lib/python3.8/site-packages/neat_python-0.92-py3.8.egg/neat/population.py", line 88, in run
  File "driver.py", line 18, in eval_genomes
    output = net.activate(xi)
  File "/home/j/anaconda3/lib/python3.8/site-packages/neat_python-0.92-py3.8.egg/neat/nn/feed_forward.py", line 13, in activate
RuntimeError: Expected 3 inputs, got 2
EN

回答 1

Stack Overflow用户

发布于 2021-09-08 18:26:34

您正在使用较新版本的示例代码。示例源注:此页面显示了GitHub上提供的当前版本的neat-python的源代码和配置文件。如果您使用的是从PyPI安装的0.92版,请确保从该版本的归档源中获取脚本和配置文件。

我在https://neat-python.readthedocs.io/en/latest/xor_example.html中检查了您的代码,它看起来是一样的,但请检查您的版本。尝试访问该版本的存档源:https://github.com/CodeReclaimers/neat-python/releases/tag/v0.92

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67118148

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档