python中map()和reduce的区别
问题来源
在使用深度学习(dl)框架时,使用函数tf.reduce_mean()后,产生了疑问,为了弄清楚其具体的意义,查找了一些资料。这里我用更直白的方式向大家解释一下python中map()
和reduce()
的用法和区别。
map()和reduce()的区别
一句话
map()
是对一个向量/矩阵中每个元素同时进行某一操作返回值与原向量维度相同;
reduce()
是对向量/矩阵一个序列中的元素依次进行某一操作,返回一个数值。
实例
map()
a = [2,4,6,8]
print map(lambda x:2*x, a)
结果为:[4, 8, 12, 16]
map()
函数的操作,是对向量a
中的每个元素,都做
2∗x
的操作。
reduce()
a = [1,2,3,4]
print reduce(lambda x,y:x+y,a)
结果为:20
reduce()
函数的操作,从第一个元素开始,将每个元素累加。换句话说,
step1:第一个元素与第二个元素相加:
2+4
得到
6
step2:step1结果和第三个元素相加:
step3:step2结果和第四个元素相加:
12+8
得到
20
拓展
tf.reduce_mean()
这是tensorflow官方文档tf.reduce_mean()
函数的说明
reduce_mean(input_tensor,reduction_indices=None,keep_dims=False, name=None)
input_tensor: The tensor to reduce. Should have numeric type.
reduction_indices: The dimensions to reduce. IfNone
(the defaut), reduces all dimensions.
# x is [[1., 1. ]]
# [2., 2.]]
tf.reduce_mean(x) ==> 1.5
tf.reduce_mean(x, 0) ==> [1.5, 1.5]
tf.reduce_mean(x, 1) ==> [1., 2.]
input_tensor
是输入的张量。
redunction_indices
进行求平均操作的维度,默认为对张量中所有元素求平均
因此不指定参数时,输出值为 1.5 ;
指定indice为0时,对每一列中的所有元素求平均,输出结果为 [1.5,1.5] ;
指定indice为1时,对每一行中的所有元素求平均,输出结果为 [1.,2.]