感知器逻辑 OR 值错误:具有多个元素的数组的真值不明确使用 a.any() 或 a.all()

问题描述

我发现了另一个标题几乎相同的问题,但它是关于逻辑与的,我在逻辑或上有问题。

这是我的代码

from numpy import array,random,dot
from random import choice
from pylab import ylim,plot

from matplotlib import pyplot as plt


def step_function(x): return 0 if x < 0 else 1


training_dataset = [

    (array([0,1,0.2345678]),1),(array([1,1]),0]),0),0.5]),]

weights = random.rand(3)

error = []

learning_rate = 0.00000001

n = 100

for j in range(n):
    x,expected = choice(training_dataset)
    result = dot(weights,x)
    err = expected - step_function(result)
    error.append(err)
    weights = weights + learning_rate * err * x

for i in range(100):

    result = dot(i,weights)

    print("{}: {} -> {}".format(i,result,step_function(result)))

ylim([-1,1])

plot(error)

plt.show()

我试图制作一个感知器。我不知道问题是什么,但是ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 当我将模型评估循环从 for i,_ in training_dataset: 更改为 for i in range(100): 时发生。我这样做是因为它只会向我显示输出 4 次,而我希望看到程序运行 100 次。你知道为什么会这样吗?我该如何解决

解决方法

for 循环迭代了 training_dataset,而不是一个范围。您需要为 dot 函数提供训练数据集。

from numpy import array,random,dot
from random import choice
from pylab import ylim,plot

from matplotlib import pyplot as plt


def step_function(x): return 0 if x < 0 else 1


training_dataset = [

    (array([0,1,0.2345678]),1),(array([1,1]),0]),0),0.5]),]

weights = random.rand(3)

error = []

learning_rate = 0.1

n = 100

for j in range(n):
    x,expected = choice(training_dataset)
    result = dot(weights,x)
    err = expected - step_function(result)
    error.append(err)
    weights = weights + learning_rate * err * x

for i in range(100):

    k = random.randint(len(training_dataset))
    
    result = dot(training_dataset[k][0],weights)

    print("{}: {} -> {}".format(i,result,step_function(result)))

ylim([-1,1])

plot(error)

plt.show()