在theano中逐行标准化矩阵

TNM*_*TNM 6 python normalization matrix theano

假设我有一个N大小的矩阵,n_i x n_o我想逐行标准化,即每行的总和应为1.我怎么能在theano做到这一点?

动机:使用softmax为我返回错误,所以我尝试通过实现我自己的softmax版本来回避它.

eic*_*erg 9

看看以下内容是否对您有用:

import theano
import theano.tensor as T

m = T.matrix(dtype=theano.config.floatX)
m_normalized = m / m.sum(axis=1).reshape((m.shape[0], 1))

f = theano.function([m], m_normalized)

import numpy as np
a = np.exp(np.random.randn(5, 10)).astype(theano.config.floatX)

b = f(a)
c = a / a.sum(axis=1)[:, np.newaxis]

from numpy.testing import assert_array_equal
assert_array_equal(b, c)
Run Code Online (Sandbox Code Playgroud)

  • 而不是`sum`之后的'reshape`,我认为`keepdims = True`在`sum`中会更清晰. (2认同)