从numpy代码中删除列表组件

时间:2014-02-14 01:09:23

标签: python arrays numpy vectorization

我正在构建一个几何神经网络,我正在遇到矢量化的问题。基本上我已经定义了一个lambda函数,它应该在作为输入提供的每个样本上运行。问题是将输入作为数组传递最方便,该数组的最后一个轴作为“样本轴”(每个索引为完整样本的轴)

我有一个有效的解决方案,基本上只是在listcomp中执行此操作,然后将其转换回numpy数组以进行其余计算。 (如果你想看到定义的任何功能,请告诉我,但我不认为它们具有很大的相关性)

class GeometricNeuralNet(object):

    def __init__(self, c, weight_domain=math.log(2)):
        """
        Dimensions of c should be a tuple that indicates the size of each layer.

        First number should be the number of input units, and the last should be the number of output units.
        Other entries should be the sizes of hidden layers.
        """
        weight_matrix = lambda a, b: np.exp(np.random.uniform(-weight_domain, weight_domain, [a,b]))
        self.weights = [weight_matrix(c[i], c[i+1]) for i in range(len(c) - 1)]
        self.predict = lambda input_vector, end=None: reduce(transfer_function, [input_vector] + self.weights[:end])

    def train(self, samples, outputs, learning_rate):
        # Forward Pass
        true_inputs = np.array([self.predict(sample, -1) for sample in samples])
        print true_inputs.shape

我对此代码的主要问题是计算true_inputs的奇怪方式。有没有办法解决? np.vectorizenp.frompyfunc似乎不允许使用轴参数,这在此非常重要。

编辑:

这是transfer_function方法。

def transfer_function(x, y):
    return gmean(np.power(x, y.T), axis=1)

1 个答案:

答案 0 :(得分:1)

你应该结帐numpy的apply_along_axis方法:http://docs.scipy.org/doc/numpy/reference/generated/numpy.apply_along_axis.html

>>> def my_func(a):
...     """Average first and last element of a 1-D array"""
...     return (a[0] + a[-1]) * 0.5
>>> b = np.array([[1,2,3], [4,5,6], [7,8,9]])
>>> np.apply_along_axis(my_func, 0, b)
array([ 4.,  5.,  6.])
>>> np.apply_along_axis(my_func, 1, b)
array([ 2.,  5.,  8.])