无法操纵列表

时间:2016-10-25 10:18:41

标签: python machine-learning neural-network

我是python的新手并尝试在python中集成我的问题域中的示例并收到以下错误:

sum_square_error += (output[0:1] - expected) ** 2
TypeError: unsupported operand type(s) for -: 'list' and 'list'

该计划:

from __future__ import print_function

import os
import numpy as np
import sys as sys

from neat import nn, population, statistics

# Network 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]

xor_inputs = [[-14.7569, 17.9667, -55.0074, -0.218445, 0.835469, 11.23]]

''',
              [-23.8745,7.40331,-48.5434,0.114681,-0.0208769,15.2138],
              [-22.2368,7.02313,-54.734,0.0633238,-0.097209,12.7707],
              [-19.0957,7.03371,-48.6117,0.108994,-0.0357287,15.205]]
'''

xor_outputs = [[-31.1812, 47.2076, -34.9315, 62.6799]]
''',
               [-53.9514,97.2412,55.7927,92.506],
               [-27.417,47.7492,-28.1557,78.6016],
               [-57.4506,99.2558,55.7436,92.3611]]
'''


def eval_fitness(genomes):
    for g in genomes:
        net = nn.create_feed_forward_phenotype(g)

        sum_square_error = 0.0
        for inputs, expected in zip(xor_inputs, xor_outputs):
            # Serial activation propagates the inputs through the entire network.
            output = net.serial_activate(inputs)
#            print(xor_inputs[0:1])
#            print(xor_outputs[0:1])
#            sys.exit(0)
            sum_square_error += (output[0] - expected) ** 2

        # When the output matches expected for all inputs, fitness will reach
        # its maximum value of 1.0.
        g.fitness = 1 - sum_square_error


local_dir = os.path.dirname(__file__)
config_path = os.path.join(local_dir, 'xor2_config')
pop = population.Population(config_path)
pop.run(eval_fitness, 300)

# Log statistics.
statistics.save_stats(pop.statistics)
statistics.save_species_count(pop.statistics)
statistics.save_species_fitness(pop.statistics)

print('Number of evaluations: {0}'.format(pop.total_evaluations))

# Show output of the most fit genome against training data.
winner = pop.statistics.best_genome()
print('\nBest genome:\n{!s}'.format(winner))
print('\nOutput:')
winner_net = nn.create_feed_forward_phenotype(winner)
for inputs, expected in zip(xor_inputs, xor_outputs):
    output = winner_net.serial_activate(inputs)
    print("expected {0:1.5f} got {1:1.5f}".format(expected, output[0]))

我搜索了错误,发现它需要转换为numpy数组。当我将xor_inputs和xor_outputs转换为numpy数组时,它会说:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

应该注意的是,xor的初始问题在2d阵列中有2个输入,在1d输出阵列中有1个输出。在我的问题中,我在2d阵列中有6个输入,在2d输出阵列中有4个输出。

1 个答案:

答案 0 :(得分:1)

虽然我没有仔细阅读你的程序,但是用list实现平方误差之和的方法是:

>>> va=[1.0, 2.0, 3.0, 4.0]
>>> vb=[0.0, 1.0, 2.0, 3.0]
>>> sum((a-b)**2 for a,b in zip(va,vb))
4.0

要理解这一点,请尝试:

>>> [(a-b)**2 for a,b in zip(va,vb)]
[1.0, 1.0, 1.0, 1.0]

您可以更轻松地使用NumPy执行此操作:

>>> import numpy as np
>>> va=np.array([1.0, 2.0, 3.0, 4.0])
>>> vb=np.array([0.0, 1.0, 2.0, 3.0])
>>> sum((va-vb)*(va-vb))
4.0

OR

>>> import numpy.linalg as la
>>> la.norm(va-vb)**2
4.0

(va-vb)*(va-vb)给出(va-vb)(va-vb)的内积,因此它的和得到(va-vb)的平方范数。 la.norm给出了给定向量的范数。

我认为上述内容对您的问题有帮助(和解决方案)。

关于这个问题:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

当您希望从布尔列表中获取布尔值时会发生这种情况。我们来看一个例子:

>>> va=np.array([1.0, 2.0, 3.0, 4.0])
>>> vb=np.array([1.0, 1.0, 2.0, 3.0])
>>> va==vb
array([ True, False, False, False], dtype=bool)

>>> 1 if va==vb else 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

现在很明显Python不理解我们是否期望它的(va == vb)或OR。 (va==vb).any()给出OR(如果至少有一个元素为真,则为true),(va==vb).all()给出AND(如果所有元素都为真,则为true)。

>>> (va==vb).any()
True
>>> (va==vb).all()
False
>>> 1 if (va==vb).all() else 0
0