在Python中结合reduce和map的最干净方法 [英] Cleanest way to combine reduce and map in Python
问题描述
我正在做一些深度学习,我想获取所有隐藏层的值.所以我最终编写了这样的函数:
I'm doing a little deep learning, and I want to grab the values of all hidden layers. So I end up writing functions like this:
def forward_pass(x, ws, bs):
activations = []
u = x
for w, b in zip(ws, bs):
u = np.maximum(0, u.dot(w)+b)
activations.append(u)
return activations
如果我不必获取中间值,那么我将使用更为冗长的形式:
If I didn't have to get the intermediate values, I'd use the much less verbose form:
out = reduce(lambda u, (w, b): np.maximum(0, u.dot(w)+b), zip(ws, bs), x)
Bam.全部一条线,美观小巧.但是我不能保留任何中间值.
Bam. All one line, nice and compact. But I can't keep any of the intermediate values.
那么,有什么方法可以让我的蛋糕(漂亮的紧凑型单缸)也可以吃掉(返回中间值)?
So, what is there any way to have my cake (nice compact one-liner) and eat it too (return intermediate values)?
推荐答案
实际上,您可以使用 result = [y for y in in [initial] for y for x in input in [f]中的y的怪异模式来执行此操作.(x,y)]]
.请注意,第一个和第三个 for
并不是真正的循环,而是赋值-我们可以在[value] 中使用 for var来理解分配
value
的方法.到 var
.例如:
You can actually do this using the somewhat weird pattern of result = [y for y in [initial] for x in inputs for y in [f(x, y)]]
. Note that the first and third for
are not really loops but assignments - we can use for var in [value]
in a comprehension to assign value
to the var
. For example:
def forward_pass(x, ws, bs):
activations = []
u = x
for w, b in zip(ws, bs):
u = np.maximum(0, u.dot(w)+b)
activations.append(u)
return activations
相当于:
def forward_pass(x, ws, bs):
return [u for u in [x] for w, b in zip(ws, bs) for u in [np.maximum(0, u.dot(w)+b)]]
Python 3.8 +:
Python 3.8引入了海象"运算符:=
,这为我们提供了另一种选择:
Python 3.8+:
Python 3.8 introduces the "walrus" operator :=
, which gives us another option:
def forward_pass(x, ws, bs):
u = x
return [u:=np.maximum(0, u.dot(w)+b) for w, b in zip(ws, bs)]
这篇关于在Python中结合reduce和map的最干净方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!