从numpy代码中删除列表推导式

3
我正在构建一个几何神经网络,但在向量化方面遇到了问题。基本上,我已经定义了一个lambda函数,它应该在提供的每个样本上运行。问题是最方便的方法是将输入作为数组传递,并将该数组的最后一个轴作为“样本轴”(每个索引都是完整样本的轴)。
我有一个解决方案,基本上只是在列表推导中执行此操作,然后将其转换回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)

我认为我们需要看到transfer_function才能帮助您。另外,您使用lambda而不是在类中定义适当的方法是否有原因? - Bi Rico
@BiRico 发布了,虽然我仍然觉得这与主题无关。主要是为了代码的清晰度而使用 lambda,不排斥编写完整方法,只是似乎并不值得编写一个完整的方法。 - Slater Victoroff
1个回答

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.])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接