Python中的AttributeError: 对象没有属性

我开始学习机器学习,并接触到了神经网络。在实现一个程序时,我遇到了这个错误。我尝试了所有可能的解决方案,但没有成功。以下是我的代码:

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.]

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注