Python中的一个简单感知器

2024-04-18 19:10:33 发布

您现在位置:Python中文网/ 问答频道 /正文

http://en.wikipedia.org/wiki/Perceptron#Example

我的问题是,为什么NAND只取2个参数并返回1:

http://en.wikipedia.org/wiki/Sheffer_stroke#Definition

为了方便您粘贴代码:

th = 0.1
learning_rate = 0.1
weights = [0, 0, 0]
training_set = [((1, 0, 0), 1), ((1, 0, 1), 1), ((1, 1, 0), 1), ((1, 1, 1), 0)]

def sum_function(values):
    return sum(value * weights[index] for index, value in enumerate(values))

while True:
    print '-' * 60
    error_count = 0
    for input_vector, desired_output in training_set:
        print weights
        result = 1 if sum_function(input_vector) > th else 0
        error = desired_output - result
        if error != 0:
            error_count += 1
            for index, value in enumerate(input_vector):
                weights[index] += learning_rate * error * value
    if error_count == 0:
        break

Tags: inorghttpforinputindexifvalue
3条回答

这是因为你需要一个恒定的输入值。-也被称为偏见。在

如果你注意到你也有三个权重,那么三元组中的第一项(似乎总是1)应该被视为“输入0”(bias)。这是一个常数。在

我建议你在youtube上看看这些视频:simple explanation of neural networks

希望这有帮助

我的答案是用Java编写的,我刚开始接触Python,所以我会在找到答案后更新它。在

boolean nand(boolean[] a) {
  boolean b = true
  if (a.length > 1) {
    b = a[0] && a[1];
    if (a.length > 2)
      for (int i = 2; i < a.length; i++)
        b &= a[i];
  }
  return !b;
}

用法(应返回true):

^{pr2}$

编辑

两年后,我又回到这个问题上来补充我的答案。。。在

我用python创建了一个迭代递归的解决方案。我还试图编写高尔夫的递归代码。我把它压缩到106字节。在

实施

迭代

def nand(*a):
    if len(a) > 1:
        b = a[0] and a[1]
        if len(a) > 2:
            for i in range(2, len(a)):
                b = b and a[i]
        return not b
    return None

递归

def nand(*a):
    if len(a) < 2:
        return None
    elif len(a) == 2:
        return not (a[0] and a[1])
    else:
        return nand(*([a[0] and a[1]] + list(a[2:])))

递归(lambda)

nand=lambda*a:None if len(a)<2 else not(a[0]and a[1])if len(a)==2 else nand(*([a[0]and a[1]]+list(a[2:])))

结果

print nand(True,  True,  True)   #  ¬(1 ∧ 1 ∧ 1) == 0
print nand(True,  True,  False)  #  ¬(1 ∧ 1 ∧ 0) == 1
print nand(True,  False, True)   #  ¬(1 ∧ 0 ∧ 1) == 1
print nand(True,  False, False)  #  ¬(1 ∧ 0 ∧ 0) == 1
print nand(False, True,  True)   #  ¬(0 ∧ 1 ∧ 1) == 1
print nand(False, True,  False)  #  ¬(0 ∧ 1 ∧ 0) == 1
print nand(False, False, True)   #  ¬(0 ∧ 0 ∧ 1) == 1
print nand(False, False, False)  #  ¬(0 ∧ 0 ∧ 0) == 1

在这个问题中,我们试图学习NAND函数。因此,输入向量(a,b,a NAND b)期望的输出是这个输入组合是正确的还是错误的,即它是否是NAND函数的正确表示。在

例如,((1,1,1), 0)表示{}是错误的,因此它被归类为0(错误)。((1,1,0), 1)表示{}是正确的,因此被归类为1(正确)。在

当其他组合作为训练数据的一部分被加入时,分类器将学习NAND函数。下面是几个可以添加到训练数据中的元组。在

((0,0,1),1)
((0,1,1),1)
((1,0,1),1)
((0,0,0),0)
((0,1,0),0)
((1,0,0),0)

相关问题 更多 >