python - 标量变量的索引无效。如何解决这个问题?
问题描述
因此,我检查了有关此问题的其他问题和答案,但我不明白原因,请您帮我解决这个问题,请
我正在学习线性回归,并使用两个变量实现了线性回归的代码。这个实现应该预测两个数字的总和,但它给出了一个错误
这里实现的代码:
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.
我不知道我做错了什么。任何帮助,将不胜感激。
解决方案
x
你传递给什么
gradientDescent(x,y)
查看回溯并尝试找出问题所在的变量 - 问题是您无法索引标量,数字。它必须是一个列表或数组。通过您的代码跟踪问题变量。
在回溯中:
在您使用
x[0]
和的问题行中x[1]
。此时是什么x
情况?在调用函数中
d
,它设置为d = x[i]
在
gradientDescent
传递的变量中再次调用d
,并设置为d = x[i]
所以你有3个索引级别。原版x
支持吗?
在尝试修复之前,您必须了解问题。
推荐阅读
- database - 如何通过多个程序员同步数据库项目的工作?
- angular - Triple DES 的实现在 CryptoJS 和 gwt-crypto 中输出不同的结果
- r - 将字符串列表分成单独的行
- ffmpeg - 将 3 个不同的视频连接在一起的最佳帧大小、比特率和帧率是多少?
- json - 如何动态修改 JSON 结构化数据,修改脚本标签内每个键的值
- javascript - 是否可以访问 iframe 之外的数组?
- javascript - 模拟 Facebook 喜欢/不喜欢系统的好习惯
- c - ISAPI 扩展是否可以与客户端断开连接
- c++ - 在这个程序中应该如何输入字符串和双精度数据类型?
- android - 将资产预处理集成到 Android Gradle 构建中