批量梯度下降算法显示 'int' 不可迭代错误

Batch Gradient descent algorithm showing 'int' not iterable error

lr = 0.1
n_iterations = 1000
m = 5

theta = np.array([[1000],[989],[123],[3455]])

for iterations in n_iterations:
    gradients = 2/m * X_b.T.dot(X_b.dot(theta) - y)
    theta = theta - lr * gradients
    
theta

执行代码后出现错误 'int' is not iterable。

更多数据:

X_b = np.asanyarray(df[['area', 'bedrooms', 'age']])

来自 csv 文件

我使用三个参数(面积、卧室、年龄)来预测价格,即 y

请帮我解决那个错误

n_iterations 是一个 int,它不像错误所说的那样是可迭代的。我想你想循环 n_iterations 次。

像这样尝试range

lr = 0.1
n_iterations = 1000
m = 5

theta = np.array([[1000],[989],[123],[3455]])

for iterations in range(n_iterations):
    gradients = 2/m * X_b.T.dot(X_b.dot(theta) - y)
    theta = theta - lr * gradients
    
theta

您正在使用 for iterations in n_iterations:,其中 n_iterations 是不应重复的整数值。你可以使用范围来克服它

for iterations in range(n_iterations):