首页 > 解决方案 > 标量变量的索引无效。如何解决这个问题?

问题描述

因此,我检查了有关此问题的其他问题和答案,但我不明白原因,请您帮我解决这个问题,请

我正在学习线性回归,并使用两个变量实现了线性回归的代码。这个实现应该预测两个数字的总和,但它给出了一个错误

这里实现的代码:

import matplotlib.pyplot as plt
import numpy as np

x = np.array([[1,1],[1,2],[2,3],[3,4],[4,5],[5,6]])
y = np.array([2,3,5,7,9,11])

#hypothesis
def hypothesis(theta, x):
    return theta[0] + theta[1]*x[0] + theta[2]*x[1]

#cost function J(t0, t1, t2)
def cost(theta, x, y):
    m = x.shape[0]
    error = 0
    for i in range(m):
        d = x[i]
        hx = hypothesis(theta, d)
        error = error + (hx - y[i])**2
    return error

#differentiation of cost function
def diffGradient(theta, x, y):
    grad = np.zeros((3,))
    m = x.shape[0]
    for i in range(m):
        hx = hypothesis(theta, x)
        grad[0] = grad[0] + (hx - y[i])
        grad[1] = grad[1] + (hx - y[i])*x[0]
        grad[2] = grad[2] + (hx - y[i])*x[1]
    return 0

#gradient descent funtion
def gradientDescent(x, y, learning_rate = 0.001):
    theta = [-2.0,0.0,1.0]
    iter = 100
    error_list = []
    theta_list = []
    for i in range(iter):
        d = x[i]
        grad = diffGradient(theta, d, y)
        e = cost(theta, d, y)
        error_list.append(e)
        theta_list.append((theta[0],theta[1],theta[2]))
        #simultaneous update
        theta[0] = theta[0] - learning_rate*grad[0]
        theta[1] = theta[1] - learning_rate*grad[1]
        theta[2] = theta[2] - learning_rate*grad[2]
    return theta, theta_list, error_list

final_theta, theta_list, error_list = gradientDescent(x,y)

在上面的行之后,我收到了这个错误

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-56-bda7687d0af9> in <module>
----> 1 final_theta, theta_list, error_list = gradientDescent(x,y)

<ipython-input-55-033133fbfbd5> in gradientDescent(x, y, learning_rate)
      8         d = x[i]
      9         grad = diffGradient(theta, d, y)
---> 10         e = cost(theta, d, y)
     11         error_list.append(e)
     12         theta_list.append((theta[0],theta[1],theta[2]))

<ipython-input-41-6a07f4b81c9c> in cost(theta, x, y)
      5     for i in range(m):
      6         d = x[i]
----> 7         hx = hypothesis(theta, d)
      8         error = error + (hx - y[i])**2
      9     return error

<ipython-input-27-43ce9d7c567b> in hypothesis(theta, x)
      1 #hypothesis
      2 def hypothesis(theta, x):
----> 3     return theta[0] + theta[1]*x[0] + theta[2]*x[1]

IndexError: invalid index to scalar variable.

我不知道我做错了什么。任何帮助,将不胜感激。

标签: pythonpython-3.xnumpy

解决方案


x你传递给什么

gradientDescent(x,y)

查看回溯并尝试找出问题所在的变量 - 问题是您无法索引标量,数字。它必须是一个列表或数组。通过您的代码跟踪问题变量。

在回溯中:

  • 在您使用x[0]和的问题行中x[1]。此时是什么x情况?

  • 在调用函数中d,它设置为d = x[i]

  • gradientDescent传递的变量中再次调用d,并设置为d = x[i]

所以你有3个索引级别。原版x支持吗?

在尝试修复之前,您必须了解问题。


推荐阅读