我目前正在尝试在python中手动实现单层感知器,并且遇到以下错误但不明白原因。
这是我的代码,以及我使用的数据集。
def predict(inVec, initWeights, bias):
activation = bias;
for i in range(len(inVec) - 1):
activation += (initWeights[i] * inVec[i])
return 1.0 if activation >= 0.0 else 0.0
def updateWeights(inVec, weights, bias, learningRate):
for row in inVec:
target = row[-1]
prediction = predict(row, weights, bias)
error = target - prediction
bias = bias + (learningRate*error)
for i in range(len(row) -1):
weights[i] = weights[i] + (learningRate*error) * row[i]
return weights
以下是一个示例数据集:
dataset = [[10, 64.0277609352, 0], [15, 0.0383577812151, 0],[20, 22.15708796, 0],[25, 94.4005135336, 1],[30, 3.8228541672, 0],[35, 62.4202896763, 1]]
这是函数的参数:
bias = 0
weights = [0,0]
learningRate = 0.01
我希望执行以下功能:print(updateWeights(dataset, bias, weights, learningRate))
但我一直收到错误:TypeError: 'int' object is not subscriptable
指向预测函数的激活更新部分。这对我来说很奇怪,因为在updateWeights函数之外单独使用该函数不会导致错误。有没有人对此有所想法?
这是完整的堆栈跟踪:
Traceback (most recent call last):
File "/Users/x/Documents/workspace/Machine Learning/Perceptron/perceptron.py", line 53, in <module>
print(updateWeights(dataset, bias, weights, learningRate))
File "/Users/x/Documents/workspace/Machine Learning/Perceptron/perceptron.py", line 24, in updateWeights
prediction = predict(row, weights, bias)
File "/Users/x/Documents/workspace/Machine Learning/Perceptron/perceptron.py", line 17, in predict
activation += (initWeights[i] * inVec[i])
TypeError: 'int' object is not subscriptable