Stan like diag_pre_multiply

Does pymc have a function like stan’s diag_pre_multiply? Or
equivalently a function to turn a 1-D vector into the diagonal of a 2-D (diagonal) matrix?

It’s probably staring me in the face but…

Theano does both. In general, multiplication in theano ultimately broadcasts along the trailing dimension.

>>> import theano
>>> import theano.tensor
>>> 
>>> x = np.random.normal(size=(4,))
>>> X = np.ones(4)
>>> 
>>> X_ = theano.tensor.diag(X)
>>> x_ = theano.shared(x).reshape((4,1))
>>> z = np.ones(shape=(4,2))
>>> Z_ = theano.shared(z)
>>> 
>>> X_.eval()
array([[1., 0., 0., 0.],
       [0., 1., 0., 0.],
       [0., 0., 1., 0.],
       [0., 0., 0., 1.]])
>>> x_.eval()
array([[-0.12179349],
       [-0.488099  ],
       [ 0.63837284],
       [-1.55128083]])
>>> Z_.eval()
array([[1., 1.],
       [1., 1.],
       [1., 1.],
       [1., 1.]])
>>> 
>>> Y_ = X_ * x_
>>> U_ = Z_ * x_
>>> 
>>> Y_.eval()
array([[-0.12179349, -0.        , -0.        , -0.        ],
       [-0.        , -0.488099  , -0.        , -0.        ],
       [ 0.        ,  0.        ,  0.63837284,  0.        ],
       [-0.        , -0.        , -0.        , -1.55128083]])
>>> U_.eval()
array([[-0.12179349, -0.12179349],
       [-0.488099  , -0.488099  ],
       [ 0.63837284,  0.63837284],
       [-1.55128083, -1.55128083]])
1 Like