【问题标题】:AttributeError in python: object has no attributepython中的AttributeError:对象没有属性
【发布时间】:2018-12-04 06:42:24
【问题描述】:

我开始学习机器学习并遇到了神经网络。在执行程序时出现此错误。我试过检查每一个解决方案,但没有运气。这是我的代码:

from numpy import exp, array, random, dot

class 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 set
inputs = 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 output
print(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 属性 self.weights() 仍然说没有这样的属性。

【问题讨论】:

  • def _init_(self):。你的意思是def __init__(self): (_ * 2)
  • @Arount 这不是我刚刚回答的吗?
  • @desertnaut 是的,比我早一分钟。
  • 谢谢desertnaut和Arount

标签: python-3.x machine-learning neural-network


【解决方案1】:

嗯,原来你的初始化方法should be named__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.]

【讨论】:

    【解决方案2】:

    你的初始化方法写错了,两个下划线__init__(self):不是一个下划线_init_(self):

    否则,好的代码!

    【讨论】:

      猜你喜欢
      • 2021-08-20
      • 2020-09-11
      • 2018-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-01
      • 2015-03-28
      • 2013-03-20
      相关资源
      最近更新 更多