使用神经网络进行回归(使用 Theano)

Using a neural network for regression (with Theano)

我是 theano 的新手,遇到了麻烦。 我正在尝试使用 theano 创建一个可用于回归任务(而不是分类任务)的神经网络 在阅读了很多教程之后,我得出的结论是,我可以通过创建一个只处理回归的输出层来做到这一点,并预先添加一个带有几个隐藏层的 "normal" 神经网络。 (但这仍然在未来)。

所以这是我的 "model":

  1 #!/usr/bin/env python
  2
  3 import numpy as np
  4 import theano
  5 import theano.tensor as T
  6
  7 class RegressionLayer(object):
  8     """Class that represents the linear regression, will be the outputlayer
  9     of the Network"""
 10     def  __init__(self, input, n_in, learning_rate):
 11         self.n_in = n_in
 12         self.learning_rate = learning_rate
 13         self.input = input
 14
 15         self.weights = theano.shared(
 16             value = np.zeros((n_in, 1), dtype = theano.config.floatX),
 17             name = 'weights',
 18             borrow = True
 19         )
 20
 21         self.bias = theano.shared(
 22             value = 0.0,
 23             name = 'bias'
 24         )
 25
 26         self.regression = T.dot(input, self.weights) + self.bias
 27         self.params = [self.weights, self.bias]
 28
 29     def cost_function(self, y):
 30         return (y - self.regression) ** 2
 31

为了像 theano 教程中那样训练模型,我尝试了以下方法:

In [5]: x = T.dmatrix('x')

In [6]: reg = r.RegressionLayer(x, 3, 0)

In [8]: y = theano.shared(value = 0.0, name = "y")

In [9]: cost = reg.cost_function(y)

In [10]: T.grad(cost=cost, wrt=reg.weights)


─────────────────────────────────────────────────────────────────────────────────────────────---------------------------------------------------------------------------         [77/1395]
TypeError                                 Traceback (most recent call last)
<ipython-input-10-0326df05c03f> in <module>()
----> 1 T.grad(cost=cost, wrt=reg.weights)

/home/name/PythonENVs/Theano/local/lib/python2.7/site-packages/theano/gradient.pyc in grad(c
ost, wrt, consider_constant, disconnected_inputs, add_names, known_grads, return_disconnected
)
    430
    431     if cost is not None and cost.ndim != 0:
--> 432         raise TypeError("cost must be a scalar.")
    433
    434     if isinstance(wrt, set):

TypeError: cost must be a scalar.

我觉得我做的和在 theanos 逻辑回归教程 (http://deeplearning.net/tutorial/logreg.html) 中做的完全一样(只用了我需要的数学),但它不起作用。那为什么我不能创建渐变?

您的成本函数可能应该是平方和。目前它是一个正方形向量,但您需要将其压缩为一个值,以便能够计算 then 标量函数的梯度。这通常是这样完成的:

def cost_function(self, y):
    return ((y - self.regression) ** 2).mean()