使用 Theano 进行线性回归 – 维度不匹配

我正在熟悉 Theano 和机器学习。为了达到这个目的,我想计算一个线性回归。我的代码灵感来自于 Theano 介绍中的逻辑回归示例

我编写了以下代码:

    import numpy    import theano    import theano.tensor as T    class LinearRegression(object):        """ 计算线性回归 """        def __init__(self, input):            """ 初始化逻辑回归的参数            参数:            -----------            :type input: theano.tensor.TensorType            :param input: 描述架构输入的符号变量(一个小批量)            """            self.W = theano.shared(                value=numpy.zeros(1, dtype=theano.config.floatX),                name='W', borrow=True            )            self.b = theano.shared(                value=numpy.zeros(1, dtype=theano.config.floatX),                name='b', borrow=True            )            self.y_pred = T.dot(input, self.W) + self.b        def errors(self, y):            """ 平方距离            参数:            ----------            :y input: array_like:            :param input: 样本数据            """            errors = y- self.y_pred            return T.sum(T.pow(errors, 2))    def sgd_optimization(learning_rate=0.0013, n_epochs=100):        """        演示线性模型的随机梯度下降优化        参数:        -----        :type learning_rate: float        :param learning_rate: 学习率(随机梯度的因子)        :type n_epochs: int        :param n_epochs: 运行优化器的最大轮数        """        x_train = numpy.random.uniform(low=-2, high = 2, size=(50,1))        epsilon =  numpy.random.normal(scale=0.01, size=50)        y_train = numpy.squeeze(2*x_train) + epsilon        costs = []        eta0, x, y = T.scalar('eta0'), T.matrix(name='x'), T.vector(name='y')        classifier = LinearRegression(input = x)        cost = classifier.errors(y)        g_W = T.grad(cost=cost, wrt=classifier.W)        g_b = T.grad(cost=cost, wrt=classifier.b)        update = [(classifier.W, classifier.W - eta0 * g_W),                   (classifier.b, classifier.b - eta0 * g_b)]        train = theano.function(inputs = [eta0],                                outputs = cost,                                updates = update,                                givens = {x: x_train, y: y_train})        for _ in range(n_epochs):            costs.append(train(learning_rate))        return costs, w    SSE, regressor = sgd_optimization()

遗憾的是,当我运行这段代码时,Python 返回了以下错误信息:

ValueError: Input dimension mis-match. (input[0].shape[0] = 1, input[1].shape[0] = 50)Apply node that caused the error: Elemwise{Composite{((-i0) + i1)}}[(0, 1)](b, CGemv{no_inplace}.0)Inputs types: [TensorType(float64, vector), TensorType(float64, vector)]Inputs shapes: [(1,), (50,)]Inputs strides: [(8,), (8,)]Inputs values: [array([ 0.]), 'not shown']HINT: Re-running with most Theano optimization disabled could give you a back-trace of when this node was created. This can be done with by setting the Theano flag 'optimizer=fast_compile'. If that does not work, Theano optimizations can be disabled with 'optimizer=None'.HINT: Use the Theano flag 'exception_verbosity=high' for a debugprint and storage map footprint of this apply node.

我怀疑错误与样本数据的维度为(50,1)而回归器的维度仅为(1,1)有关。尽管如此,我尝试了一段时间也没能纠正代码中的错误。有人能提供一些如何纠正这个错误的提示吗?我对任何帮助都表示感谢!


回答:

你需要对 b 进行广播:

self.y_pred = T.dot(input, self.W) + self.b[:, None]

我原本期望 Theano 会自动完成这个操作,但似乎并非如此。


要定位问题,请按照错误消息的建议,运行 Theano 并设置高异常详细度

$ THEANO_FLAGS='exception_verbosity=high' python path/to/script.py

这会产生大量输出,包括有问题的节点及其操作数

Debugprint of the apply node:Elemwise{Composite{((-i0) + i1)}}[(0, 1)] [@A] <TensorType(float64, vector)> '' |b [@B] <TensorType(float64, vector)> |CGemv{no_inplace} [@C] <TensorType(float64, vector)> ''   |<TensorType(float64, vector)> [@D] <TensorType(float64, vector)>   |TensorConstant{-1.0} [@E] <TensorType(float64, scalar)>   |<TensorType(float64, matrix)> [@F] <TensorType(float64, matrix)>   |W [@G] <TensorType(float64, vector)>   |TensorConstant{1.0} [@H] <TensorType(float64, scalar)>

该节点对应于从临时节点 CGemv{no_inplace} 中减去 b。涉及 b 的唯一代码行是

self.y_pred = T.dot(input, self.W) + self.b

Related Posts

Keras Dense层输入未被展平

这是我的测试代码: from keras import…

无法将分类变量输入随机森林

我有10个分类变量和3个数值变量。我在分割后直接将它们…

如何在Keras中对每个输出应用Sigmoid函数?

这是我代码的一部分。 model = Sequenti…

如何选择类概率的最佳阈值?

我的神经网络输出是一个用于多标签分类的预测类概率表: …

在Keras中使用深度学习得到不同的结果

我按照一个教程使用Keras中的深度神经网络进行文本分…

‘MatMul’操作的输入’b’类型为float32,与参数’a’的类型float64不匹配

我写了一个简单的TensorFlow代码,但不断遇到T…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注