在函数返回矢量使用numpy的矢量

编程入门 行业动态 更新时间:2024-10-11 05:27:35
本文介绍了在函数返回矢量使用numpy的矢量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

numpy.vectorize 需要一个函数f:A-> B,并把它变成G:一[] - >乙:[]

numpy.vectorize takes a function f:a->b and turns it into g:a[]->b[].

这工作得很好,当 A 和 B 是标量,但我想不出理由,为什么它不会用b工作作为 ndarray 或列表,即F:A-> b []和G:一[] - >乙:[] []

This works fine when a and b are scalars, but I can't think of a reason why it wouldn't work with b as an ndarray or list, i.e. f:a->b[] and g:a[]->b[][]

例如:

import numpy as np def f(x): return x * np.array([1,1,1,1,1], dtype=np.float32) g = np.vectorize(f, otypes=[np.ndarray]) a = np.arange(4) print(g(a))

这产生:

array([[ 0. 0. 0. 0. 0.], [ 1. 1. 1. 1. 1.], [ 2. 2. 2. 2. 2.], [ 3. 3. 3. 3. 3.]], dtype=object)

好了,所以,让正确的价值观,但错误DTYPE。更糟糕的:

Ok, so that gives the right values, but the wrong dtype. And even worse:

g(a).shape

收益率:

(4,)

所以这个数组是pretty无用。我知道我可以把它转换这样做的:

So this array is pretty much useless. I know I can convert it doing:

np.array(map(list, a), dtype=np.float32)

给我我想要的:

array([[ 0., 0., 0., 0., 0.], [ 1., 1., 1., 1., 1.], [ 2., 2., 2., 2., 2.], [ 3., 3., 3., 3., 3.]], dtype=float32)

但既没有效率也没有Python的。可以在任何你们的找到一个更清洁的方式做到这一点?

but that is neither efficient nor pythonic. Can any of you guys find a cleaner way to do this?

在此先感谢!

推荐答案

np.vectorize 仅仅是一个方便的功能。实际上它并不使code跑得更快。如果不方便使用 np.vectorize ,简单地写自己的函数,如你所愿的作品。

np.vectorize is just a convenience function. It doesn't actually make code run any faster. If it isn't convenient to use np.vectorize, simply write your own function that works as you wish.

的目的 np.vectorize 是把不属于numpy的感知功能(如采取花车作为输入,并返回彩车作为输出)成可以操作的功能(和返回)numpy的数组。

The purpose of np.vectorize is to transform functions which are not numpy-aware (e.g. take floats as input and return floats as output) into functions that can operate on (and return) numpy arrays.

您函数˚F已经numpy的感知 - 它用在定义中有numpy的数组,并返回一个numpy的数组。因此, np.vectorize 不是一个好适合您的使用情况。

Your function f is already numpy-aware -- it uses a numpy array in its definition and returns a numpy array. So np.vectorize is not a good fit for your use case.

解决方案,因此刚刚推出自己的功能˚F的作品,你的愿望的方式。

The solution therefore is just to roll your own function f that works the way you desire.

更多推荐

在函数返回矢量使用numpy的矢量

本文发布于:2023-11-22 02:18:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1615586.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:矢量   函数   numpy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!