为何会报‘P对象没有iterations属性’的AttributeError错误?
问题分析与解决
出现AttributeError: 'P' object has no attribute 'iterations'的常见原因及对应解决办法:
交互式环境中未重新加载类定义
如果你在Jupyter Notebook、IPython这类交互式环境中运行代码,修改P类的定义后,必须重新执行类的定义代码块。否则创建的实例会沿用修改前的类结构,旧类可能没有iterations属性。解决办法:重新运行包含class P:的代码块,再实例化调用。拼写错误
检查两处关键位置的拼写:__init__方法中self.iterations = iterations的属性名是否正确;fit方法中range(self.iterations)的属性名是否和__init__中的一致。
从你贴的代码看拼写没问题,但实际运行时可能存在笔误,需仔细核对。
实例属性被意外删除
如果在调用c.fit()之前,执行过类似del c.iterations的代码,会导致实例丢失该属性。检查调用代码前的逻辑,确保没有误删属性的操作。
另外,你的代码还有两处潜在问题:
fit方法的返回值标注-> NoReturn需要先导入NoReturn类型;- 调用代码中使用了
make_blobs但未导入该函数。
验证后的完整可运行代码
import numpy as np from typing import NoReturn from sklearn.datasets import make_blobs class P: def __init__(self, iterations: int = 100): self.w = None self.iterations = iterations self.classes_map = None def fit(self, X: np.ndarray, y: np.ndarray) -> NoReturn: X = np.hstack((np.ones((X.shape[0], 1)), X)) self.w = np.zeros(X.shape[1]) classes = np.unique(y) self.classes_map = {-1: classes[0], 1: classes[1]} y_ = np.where(y == classes[0], -1, 1) for _ in range(self.iterations): predictions = np.sign(X.dot(self.w)) incorrect_indices = predictions != y_ if np.any(incorrect_indices): self.w += np.dot(y_[incorrect_indices], X[incorrect_indices]) def predict(self, X: np.ndarray) -> np.ndarray: X = np.hstack((np.ones((X.shape[0], 1)), X)) predictions = np.sign(X.dot(self.w)) predictions[predictions == -1] = self.classes_map[-1] predictions[predictions == 1] = self.classes_map[1] return predictions # 调用代码 X, true_labels = make_blobs(400, 2, centers=[[0, 0], [2.5, 2.5]]) c = P() c.fit(X, true_labels) print(c.predict(X[:5])) # 测试预测功能
内容的提问来源于stack exchange,提问作者Lib
相关产品推荐
相关产品推荐

