使用 theano 在逻辑回归中广播共享变量

Broadcasting of shared variables in logistic regression with theano

我目前正在通过 theano tutorial 进行逻辑回归,非常像本文 post 中所讨论的: theano 中的逻辑回归负对数似然看起来像什么。然而,原来的 tutorial 使用 共享变量 W 和 b,以及一个名为 input 的矩阵。输入是 n x n_in 矩阵,W 是 n_in x n_out,b 是 n_out x 1 列向量。

    self.W = theano.shared(
        value=numpy.zeros(
            (n_in, n_out),
            dtype=theano.config.floatX
        ),
        name='W',
        borrow=True
    )

    self.b = theano.shared(
        value=numpy.zeros(
            (n_out,),
            dtype=theano.config.floatX
        ),
        name='b',
        borrow=True
    )

    self.p_y_given_x = T.nnet.softmax(T.dot(input, self.W) + self.b)

现在,据我从共享变量的文档中了解到,共享变量的广播模式默认为 false。那么为什么这行代码不会因为尺寸不匹配而抛出错误呢?

self.p_y_given_x = T.nnet.softmax(T.dot(input, self.W) + self.b)

毕竟,我们是将矩阵 T.dot(input, self.W) 添加到向量 b。毕竟共享变量默认广播吗?即使有广播,维度也不会加起来。 T.dot(input, self.W)n x n_out 矩阵,b 是 n_out x 1 向量。

我错过了什么?

默认情况下共享变量不可广播,因为它们的形状可以改变,但是,当请求向矩阵添加标量、向矩阵添加向量等操作时,Theano 会使用张量进行必要的广播。查看 documentation 了解更多详情。 请注意 input 是符号变量而不是共享变量。如果 self.W 的第二个维度即 n_out 与向量 b 的第一个维度不同,则会发生维度不匹配,但事实并非如此在这里,所以他们完美地加起来,在 numpy 中也是一样的:

import numpy as np
a = np.asarray([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
b = np.asarray([1,2,3])
print(a + b)