我开始学习机器学习,并接触到了神经网络。在实现一个程序时,我遇到了这个错误。我尝试了所有可能的解决方案,但没有成功。以下是我的代码:
from numpy import exp, array, random, dotclass neural_network: def _init_(self): random.seed(1) self.weights = 2 * random.random((2, 1)) - 1 def train(self, inputs, outputs, num): for iteration in range(num): output = self.think(inputs) error = outputs - output adjustment = 0.01*dot(inputs.T, error) self.weights += adjustment def think(self, inputs): return (dot(inputs, self.weights))neural = neural_network()# The training setinputs = array([[2, 3], [1, 1], [5, 2], [12, 3]])outputs = array([[10, 4, 14, 30]]).T# Training the neural network using the training set.neural.train(inputs, outputs, 10000)# Ask the neural network the outputprint(neural.think(array([15, 2])))
当运行neural.train
时,我得到了以下错误:
Traceback (most recent call last):File "neural.py", line 27, in <module> neural.train(inputs, outputs, 10000)File "neural.py", line 10, in train output = self.think(inputs)File "neural.py", line 16, in think return (dot(inputs, self.weights))AttributeError: 'neural_network' object has no attribute 'weights'
尽管它确实有self.weights这个属性,但它仍然说没有这个属性。
回答:
原来,你的初始化方法应该命名为__init__
(两个下划线),而不是_init_
…
因此,将方法改为
def __init__(self): random.seed(1) self.weights = 2 * random.random((2, 1)) - 1
你的代码就能正常工作了:
neural.train(inputs, outputs, 10000)print(neural.think(array([15, 2])))# [ 34.]