Python 实现感知器功能,得到TypeError:';int对象不可下标';

Python 实现感知器功能,得到TypeError:';int对象不可下标';,python,machine-learning,perceptron,Python,Machine Learning,Perceptron,我目前正在尝试用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

我目前正在尝试用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(数据集、偏差、权重、学习率))

但我一直收到一个错误:
TypeError:“int”对象不可下标
,它指向predict函数的激活更新部分。这对我来说很奇怪,因为在updatewights函数之外单独使用该函数不会导致错误。有人对此有想法吗

以下是完整的堆栈跟踪:

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
回溯(最近一次呼叫最后一次):
文件“/Users/x/Documents/workspace/Machine Learning/Perceptron/Perceptron.py”,第53行,在
打印(更新权重(数据集、偏差、权重、学习率))
文件“/Users/x/Documents/workspace/Machine Learning/Perceptron/Perceptron.py”,第24行,在updateWeights中
预测=预测(行、权重、偏差)
文件“/Users/x/Documents/workspace/Machine Learning/Perceptron/Perceptron.py”,预测中第17行
激活+=(初始权重[i]*inVec[i])
TypeError:“int”对象不可下标

发布完整的堆栈跟踪。但是很明显,您正在迭代
int
s中的某个iterable,然后尝试索引
int
,这会抛出错误。@juanpa.arrivillaga我刚刚添加了完整堆栈跟踪,对此表示抱歉。
打印(updatewights(dataset,bias,weights,learningRate))
与您的函数def不同。偏移和权重是交换的。这也会导致predict中的错误用法。@sascha谢谢,解决了这个问题。