我正在尝试在Python中使用自动差异化来实现成本函数。我遇到了一些困难,因为我无法区分NumPy数组和autograd
ArrayBox;错误是
ValueError: setting an array element with a sequence.
我使用的代码是:
import autograd.numpy as np
from autograd import grad
n = 11 # Number of rows from original dataset
data = np.transpose(mcn_observed[:n+1, :])
# mcn_observed is simply a dataset imported with Pandas and
# converted to a NumPy array. 5000 rows and 10 columns
def cost(w):
# Cost function for autograd
output = np.empty((10,n))
output[:, 0] = 0.1 * np.ones((10))
W = w[:, :10] # Matrix of weights
k = w[:, 10] # Vector of bias
for i in range(1, n):
# Euler's method for ODE
lhs = np.dot(W, output[:, i-1]) - k*output[:, i-1]
lhs = 0.1 * lhs
output[:,i] = output[:, i-1] + lhs.reshape(output[:, i-1].shape)
# Take difference between simulated and observed data
r = np.asarray(output - data)
return sum(sum(r))
# Initialize matrix of weights and bias
W = np.random.rand(10,11) + 1.0
for j in range(10):
print("Iteration: {}".format(j))
g = grad(cost)(W)
W = W - 0.01 * g # Gradient descent
错误似乎在output[:,i] = output[:, i-1] + lhs.reshape(output[:, i-1].shape)
。
答案 0 :(得分:0)
我遇到了同样的问题。尝试将autograd ArrayBox分配给numpy数组时,似乎会发生这种情况。目前对我来说没有任何意义...
这是导致此问题的非常简单的代码:
import autograd.numpy as np
from autograd import grad
def fun(x):
a = np.zeros((1,))
a[0] = x**2
return a
if __name__ == '__main__':
print(fun(1.0))
gradfun = grad(fun)
print(gradfun(1.0))