gpt4 book ai didi

python-3.x - 在 Python 中实现感知器算法时遇到问题

转载 作者:行者123 更新时间:2023-11-30 09:17:22 25 4
gpt4 key购买 nike

由于某种原因,我在调试以下代码时遇到问题感知器在使用随机值作为权重的几个步骤后停止 self 更新。我尝试过不使用类来完成我的工作,并将所有内容编辑到最低限度,但仍然遇到同样的问题。我还检查了 Perceptron.train(),它工作得很好。所以,我猜主要问题是火车功能本身。我对 python 编程有点陌生,所以任何帮助将不胜感激。 随机导入 将绘图导入为 plt 将 numpy 导入为 np

#-----Function Of the line that seperates the two different Data Types-----$
def f(x):
return x

#-----Activation Function-----#
def act(x):
if x >= 0:
return 1.0
return 0.0

class Point:

def __init__(self, x, y):
self.X = x
self.Y = y
if y > f(x):
self.Target = 1.0
else:
self.Target = 0.0


class Perceptron:

def __init__(self, n, actFunc = act, lr = 0.2):
self.Weights = [0 for i in range(n)]
self.ActFunc = actFunc
self.LR = lr

def guess(self, inputs):
valSum = 0
for i in range(len(inputs)):
valSum += self.Weights[i] * inputs[i]
return self.ActFunc(valSum)

def train(self, inputs, target):
cal = self.guess(inputs)
err = target - cal
for i in range(0, len(self.Weights)):
self.Weights[i] += self.LR * err * inputs[i]

def printWeights(self):
for i in range(len(self.Weights)):
print("WEIGHT[" + str(i) + "] = " + str(self.Weights[i]))
print("")

def lineFunc(self):
# y = w0 + w1x + w2y
# (1 - w2)y = w0 + w1x
# y = w0/(1-w2) + w1/(1 - w2)x
w0 = self.Weights[0]
w1 = self.Weights[1]
w2 = self.Weights[2]
return (str(w0/(1 - w2)) + " + " + str(w1/(1 - w2)) + " * x")

#-----INITIALISING DATA------#
brain = Perceptron(3)

n = 20
points = [Point(random.uniform(-10, 10), random.uniform(-10, 10)) for x in range(n)]

t = 1000

#-----Training-----#
for i in range(t):
point = points[random.randrange(0, n)]
brain.train([1, point.X, point.Y], point.Target)
brain.printWeights()
print(brain.lineFunc())

最佳答案

我自己确实发现了这个问题。 LineFunc() 方法中存在错误。返回值错误,应该是:

    return (str(-w0/w2) + " + " + str(-w1/w2) + " * x")

关于python-3.x - 在 Python 中实现感知器算法时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51831855/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com