【问题标题】:Perform numpy exp function in-place就地执行 numpy exp 函数
【发布时间】:2016-12-20 15:25:22
【问题描述】:

如标题所示,我需要在一个非常大的 ndarray 上执行numpy.exp,比如说ar,并将结果存储在ar 本身中。这个操作可以原地执行吗?

【问题讨论】:

  • 我不确定您是否可以在不临时分配数组的情况下执行此操作。如果可以的话,我看不出这将如何与 numpy 中的快速矢量化一起工作。
  • ar = np.exp(ar) 有什么问题。 @AndrasDeak,你是这个意思吗?
  • @piRSquared 我认为 OP 的观点是,如果他们在ar 中有 6 GB RAM 和 5 GB,他们就不能暂时分配 np.exp(ar)ar。是的,如果你可以临时分配,那么做这样的事情很简单:)
  • @AndrasDeak 我明白了。

标签: python-3.x numpy multidimensional-array exp numpy-ndarray


【解决方案1】:

您可以使用exp的可选out参数:

a = np.array([3.4, 5])
res = np.exp(a, a)
print(res is a)
print(a)

输出:

True
[  29.96410005  148.4131591 ]

exp(x[, out])

计算输入数组中所有元素的指数。

返回

输出:ndarray 输出数组,x 的元素指数。

这里a 的所有元素都将替换为exp 的结果。返回值resa 相同。没有创建新数组

【讨论】:

  • 这可能是最节省内存的解决方案。我仍然认为np.exp 内部有内部分配,但它可能不会比这更好。
  • 感谢您的回答。下次我会仔细看看文档!
  • 我认为在提供out 时没有内部分配。
【解决方案2】:

Mike Mueller's 答案很好,但请注意,如果您的数组类型为int32intint64 等,它将抛出TypeError。因此,执行此操作的安全方法是将数组类型转换为 float64float32 等,执行 exp 之类的操作之前,

In [12]: b
Out[12]: array([1, 2, 3, 4, 5], dtype=int32)

In [13]: np.exp(b, b)
--------------------------------------------------------------------------
TypeError: ufunc 'exp' output (typecode 'd') could not be coerced to provided 
output parameter (typecode 'i') according to the casting rule ''same_kind''

类型转换和exp:

# in-place typecasting
In [14]: b = b.astype(np.float64, copy=False)
In [15]: b
Out[15]: array([ 1.,  2.,  3.,  4.,  5.], dtype=float64)

# modifies b in-place
In [16]: np.exp(b, b)
Out[16]: array([   2.718,    7.389,   20.086,   54.598,  148.413], dtype=float64)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-13
    • 1970-01-01
    • 2015-02-18
    • 1970-01-01
    • 2017-12-25
    • 2017-08-26
    • 2011-07-16
    • 1970-01-01
    相关资源
    最近更新 更多