我是theano的新手,我遇到了麻烦。 我正在尝试使用theano创建一个可用于回归任务的神经网络(而不是分类任务) 在阅读了很多教程之后,我得出的结论是,我可以通过创建一个只处理回归的输出层来做到这一点,并预备一个带有一些隐藏层的“普通”神经网络。 (但这仍然存在于未来)。
所以这是我的“模特”:
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.
我觉得我完全一样(只有我需要的数学),就像在逻辑回归教程(http://deeplearning.net/tutorial/logreg.html)中完成的那样,但它不起作用。那么为什么我不能创建渐变?
答案 0 :(得分:1)
您的成本函数应该是平方和。目前它是一个正方形矢量,但你需要将其压缩到一个值,以便能够使用当时标量函数的梯度。这通常是这样做的:
def cost_function(self, y):
return ((y - self.regression) ** 2).mean()