Python-报错setting an array element with a sequence. 机器学习 regression

本人Python刚入门,目前自学机器学习。有一行代码一直显示setting an array element with a sequence. 实在不知道怎么改,望大家帮忙解惑。非常感谢~~
第一次提问,若有不对望指出~
#machine learning - regression

import numpy as np
import matplotlib.pyplot as plt

# Define the input data
x_data = [ 338., 333., 328., 207., 226., 25., 179., 60., 208., 606., ]
y_data = [ 640., 633., 619., 393., 428., 27., 193., 66., 226., 1591., ]

# Define the range of values for bias and weight
x = np.arange(-200, -100, 1) # bias
y = np.arange(-5, 5, 0.1) # weight

# Create a meshgrid of the bias and weight values
x, y = np.meshgrid(x, y)

# Initialize the cost matrix with zeros
z = np.zeros((len(x), len(y)))

# Calculate the cost for all combinations of bias and weight
for i in range(len(x)):
    for j in range(len(y)):
        b = x[i]
        w = y[j]
        z[j][i] = 0
        for n in range(len(x_data)):
            _**z[j][i] = z[j][i] + (y_data[n] - b - w * x_data[n])**2**_  #(就是这一行,一直报错,,,)
        z[j][i] = z[j][i] / len(x_data)

# Set the initial values for bias, weight, learning rate, and number of iterations
b = -120 # initial bias
w = -4 # initial weight
lr = 0.0000001 # learning rate
iteration = 100000 # number of iterations

# Store the initial values for plotting
b_history = [b]
w_history = [w]

# Perform gradient descent
for i in range(iteration):
    b_grad = 0.0
    w_grad = 0.0
    for n in range(len(x_data)):
        b_grad = b_grad - 2.0 * (y_data[n] - b - w * x_data[n]) * 1.0
        w_grad = w_grad - 2.0 * (y_data[n] - b - w * x_data[n]) * x_data[n]

    # Update the bias and weight values
    b = b - lr * b_grad
    w = w - lr * w_grad

    # Store the updated values for plotting
    b_history.append(b)
    w_history.append(w)

# Plot the results
plt.contourf(x, y, z, 50, alpha=0.5, cmap=plt.get_cmap('jet'))
plt.plot(b_history, w_history, 'o-', ms=3, lw=1.5, color='black')
plt.plot([-188.4], [2.67], 'x', ms=12, markeredgewidth=3)



img


你的b,w是数组,x,y是数值,没办法进行运算


z[j][i] = z[j][i] + (y_data[n] - b - w * x_data[n])**2

z[j][i] 已经在之前被初始化为零,然后尝试将 z[j][i] 设置为 (y_data[n] - b - w * x_data[n])**2,以计算每个不同偏置和权重组合的成本。问题在于,在第二次循环中,z[j][i] 的值被覆盖,因此会发生索引错误。解决此问题的方法是将 z 矩阵的索引顺序更改为 z[i][j],以使其与 x 和 y 矩阵保持一致。因此,这行代码应更改为:

z[i][j] = z[i][j] + (y_data[n] - b - w * x_data[n])**2
不知道你这个问题是否已经解决, 如果还没有解决的话:
  • 这篇博客: ValueError: setting an array element with a sequence.中的 机器学习问题记录:ValueError: setting an array element with a sequence. 部分也许能够解决你的问题, 你可以仔细阅读以下内容或者直接跳转源博客中阅读:

    最近在学习吴恩达老师的机器学习课程,在完成ex2的作业过程中,python报错:ValueError: setting an array element with a sequence.
    百度发现遇到此问题的人不少,但原因可能有所不同,现将个人的问题解决过程记录如下:


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^