python - 神经网络优化失败(使用 Scipy fmin_cg)

标签 python numpy scipy neural-network backpropagation

简单介绍一下:我正在尝试实现一个 3 层神经网络(1 个隐藏层),用于 Cifar-10 数据集上的图像分类。我已经实现了反向传播,最初尝试简单地使用梯度下降来训练网络,但我的成本稳定在 40 左右(这以与随机猜测相同的速率有效地对新图像进行分类;实际上毫无意义)。

然后我尝试使用 scipy.optimize.fmin_cg 函数来训练网络。我将展开的权重传递给函数,并且我的反向传播函数返回相同大小的梯度向量,这满足了函数的输入要求。

我的函数实现如下所示:

scipy.optimize.fmin_cg(cost, iw, fprime=fit_slim)

其中 fitfit_slim 函数如下:

def fit(X, Y, w, l, predict=False, x=None):
    w_grad = ([np.mat(np.zeros(np.shape(w[i]))) 
              for i in range(len(w))])
    for i in range(len(X)):
        x = x if predict else X[i]
        y = Y[i]
        # forward propagate
        a = x
        a_s = []
        for j in range(len(w)):
            a = np.mat(np.append(1, a)).T
            a_s.append(a)
            z = w[j] * a
            a = sigmoid(z)
        if predict: return a
        # backpropagate
        delta = a - y.T
        w_grad[-1] += delta * a_s[-1].T
        for j in reversed(range(1, len(w))):
            delta = delta[1:] if j != len(w)-1 else delta
            delta = np.multiply(w[j].T*delta, s_prime(a_s[j]))
            w_grad[j-1] += (delta[1:] * a_s[j-1].T)
    # regularization
    for i in range(len(w)):
        w_grad[i] /= len(X)
        w_grad[i][:,1:] += (l/len(X)) * w[i][:,1:]
    return flatten(w_grad).T

def fit_slim(iw):
    iw = shape_back(iw)
    return fit(X, Y, iw, l)

成本函数是:

def cost(iw):
    J = 0
    m = len(X)
    iw = shape_back(iw)
    for i in range(m):
        h = fit(X, Y, iw, l, True, X[i])
        J += ((1.0/m)*(np.sum((np.multiply(-Y[i],np.log(h))-
              np.multiply((1-Y[i]),np.log(1-h))).flatten())))
    for i in range(len(w)):
        J += np.sum(((l/(2.0*m))*np.power(w[i],2)).flatten())
    return J

iw 变量是将权重展开为一个长向量,而 shape_back 函数只是将 iw reshape 回其原始矩阵形状在 fitcost 函数中使用。

我面临的第一个问题是我的 fit 函数需要永远运行一次迭代。我所说的永远是指大​​约一分钟,这看起来很慢。尽管如此,正如我所提到的,我让它一直运行到成本稳定在 40 左右,这仍然是一个非常高的成本。也就是说,实现替代优化技术对我来说似乎是合理的,我解决了 fmin_cg 函数。

当我运行它时,我收到以下错误:

  File "image_net.py", line 143, in <module>
    print scipy.optimize.fmin_cg(cost, iw, fprime=fit_slim, maxiter=2,  callback=callback)
  File "/Users/samgriesemer/anaconda/lib/python2.7/site-packages/scipy/optimize/optimize.py", line 1092, in fmin_cg
    res = _minimize_cg(f, x0, args, fprime, callback=callback, **opts)
  File "/Users/samgriesemer/anaconda/lib/python2.7/site-packages/scipy/optimize/optimize.py", line 1156, in _minimize_cg
    deltak = numpy.dot(gfk, gfk)
ValueError: shapes (616610,1) and (616610,1) not aligned: 1 (dim 1) != 616610 (dim 0)

在我看来,该函数正在尝试获取同一向量的点积,这对我来说没有任何意义。

回顾一下我的问题,我有两个问题。

1) 我可以做些什么来更好地优化我的 fit 函数吗?我的数据集有 10,000 个示例,所以我明白循环所有这些示例需要时间,但它不明白为什么即使经过多次迭代,我的成本仍然很高。

2) 为什么我在运行 fmin_cg 函数时收到错误?我传递给函数的参数是相同大小的向量。我不明白为什么它会尝试在函数内获取相同大小向量的点积。

非常感谢任何能够阐明这些问题/误解的人。

最佳答案

It seems to me that the function is attempting to take the dot product of the same vector, which doesn't make any sense to me.

这不是numpy.dot作品。问题正是错误消息所说的那样:它尝试执行矩阵乘法,但由于维度不匹配而失败。

请注意,对于可以视为“一维”的数组,numpy 会区分形状 (n,) , (n, 1)(1, n) :对于 numpy,只有第一个是一维,并且它被解释为行或列向量。

>>> a = np.ones(3)      # a 1D array
>>> np.dot(a, a)
3.0
>>> b = a.reshape(-1, 1)   # a column vector
>>> b
array([[ 1.],
       [ 1.],
       [ 1.]])
>>> np.dot(b, b)           # column times column, fails
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: shapes (3,1) and (3,1) not aligned: 1 (dim 1) != 3 (dim 0)
>>> np.dot(b, b.T)        # column times row, i.e. an outer product
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.],
       [ 1.,  1.,  1.]])
>>> np.dot(b.T, b)        # row times column, but notice the dimensions
array([[ 3.]])            

关于python - 神经网络优化失败(使用 Scipy fmin_cg),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36457130/

相关文章:

python - 元组列表的列表,按第一个元素分组并添加第二个元素

python - 使用 numpy 'module' 对象没有属性 'array'

python - 如何在不同标题的python中加入时间序列数据?

python - Python 中的二维最近邻插值

python - 查找具有特定类的 div 的后代

python - iPython:类似操作的命令

python - Numpy 类型错误 : only length-1 arrays can be converted to Python scalars (reshape)

python - scipy.integrate.odeint 和 scipy.integrate.ode 有什么区别?

python - 如何调整 N 维 numpy 图像的大小?

python - 需要降级 pandas 版本,但出现 "ModuleNotFoundError"错误