gpt4 book ai didi

python - 从 numpy 代码中删除列表组件

转载 作者:行者123 更新时间:2023-11-28 18:44:52 25 4
gpt4 key购买 nike

我正在构建一个几何神经网络,但遇到了矢量化问题。基本上我定义了一个 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)

最佳答案

您应该检查 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.])

关于python - 从 numpy 代码中删除列表组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21769010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com