我知道这对于其他人来说并不是一个非常普遍或适用的问题,但它让我感到困惑,并且可能教会我比我想象的更多的东西。
def gradient_descent((x,y)):
x = (x,y)[0]
y = (x,y)[1]
point_history_x[0] = x
point_history_y[0] = y #set initial states
while numpy.linalg.norm(f_prime((x,y))) >= 0.1: #modulus of gradient
x = x - gamma*f_prime((x,y))[0]
y = y - gamma*f_prime((x,y))[1] #find next point
numpy.append(point_history_x,x)
numpy.append(point_history_y,y) #add to history of point movement
return point_history_x, point_history_y
之前,point_history_x(和 y)在全局范围内定义为 numpy.zeros((1))。 当针对点 (0,0) 运行时,它会为两个历史数组返回 0。当我自己将每个关卡输入 python shell 时,它工作正常并创建一个变体 x 的数组;但是当我运行该模块时,它只返回输入。
所有证据似乎都表明我错误地使用了追加,但正如我所说,我在 shell 中输入相同的内容并且运行良好。
这真的很令人沮丧,任何评论将不胜感激。
最佳答案
在这种情况下,Append 返回一个新数组。它不会改变point_history_x
。
>>> import numpy as np
>>> a = np.array([2.0])
>>> np.append(a, 1)
array([ 2., 1.])
>>> a
array([ 2.])
>>> a = np.append(a, 1)
>>> a
array([ 2., 1.])
>>>
我们看到的是 np.append
有效 - 没有异常或任何东西 - 但 a
没有被调用修改,它只是返回一个新数组。第二次调用 np.append
时,我通过将结果分配给 a
来保存结果。
代码的其他部分还存在一些非常规/冗余的内容。元组参数解包并不像以前那样理想removed in Python 3 (以为 2to3 会自动为你转换)但主要原因是它只是让事情变得更加复杂。你可以改变
def gradient_descent((x,y)):
x = (x,y)[0]
y = (x,y)[1]
到任一
def gradient_descent(pt):
x, y = pt
或
def gradient_descent(x,y):
并使用gradient_descent(*pt)
调用代码。
我还认为,对于 point_history_x
和 point_history_y
使用普通的 Python 列表会更好。使用 NumPy 数组,您最终将在循环的每次迭代中分配大量内存。
关于python - numpy.append() 的困难。当我自己在 IDLE 中输入它时它有效,但在运行时无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20177617/