编写函数以处理向量和矩阵(Writing functions to work on vectors and matrices)

编程入门 行业动态 更新时间:2024-10-23 09:38:53
编写函数以处理向量和矩阵(Writing functions to work on vectors and matrices)

作为更大函数的一部分,我写了一些代码来生成包含输入向量/矩阵'x'的每列的平均值的向量/矩阵(取决于输入)。 这些值存储在与输入矢量形状相同的矢量/矩阵中。

我的初步解决方案是在一维和矩阵阵列上工作,非常麻烦:

# 'x' is of type array and can be a vector or matrix. import scipy as sp shp = sp.shape(x) x_mean = sp.array(sp.zeros(sp.shape(x))) try: # if input is a matrix shp_range = range(shp[1]) for d in shp_range: x_mean[:,d] = sp.mean(x[:,d])*sp.ones(sp.shape(z)) except IndexError: # error occurs if the input is a vector z = sp.zeros((shp[0],)) x_mean = sp.mean(x)*sp.ones(sp.shape(z))

从MATLAB背景来看,这就是它在MATLAB中的样子:

[R,C] = size(x); for d = 1:C, xmean(:,d) = zeros(R,1) + mean(x(:,d)); end

这适用于矢量以及矩阵,没有错误。

我的问题是,如何使我的python代码在没有(丑陋)try / except块的情况下输入向量和矩阵格式?

谢谢!

As part of a larger function, I'm writing some code to generate a vector/matrix (depending on the input) containing the mean value of each column of the input vector/matrix 'x'. These values are stored in a vector/matrix of the same shape as the input vector.

My preliminary solution for it to work on both a 1-D and matrix arrays is very(!) messy:

# 'x' is of type array and can be a vector or matrix. import scipy as sp shp = sp.shape(x) x_mean = sp.array(sp.zeros(sp.shape(x))) try: # if input is a matrix shp_range = range(shp[1]) for d in shp_range: x_mean[:,d] = sp.mean(x[:,d])*sp.ones(sp.shape(z)) except IndexError: # error occurs if the input is a vector z = sp.zeros((shp[0],)) x_mean = sp.mean(x)*sp.ones(sp.shape(z))

Coming from a MATLAB background, this is what it would look like in MATLAB:

[R,C] = size(x); for d = 1:C, xmean(:,d) = zeros(R,1) + mean(x(:,d)); end

This works on both vectors as well as matrices without errors.

My question is, how can I make my python code work on input of both vector and matrix format without the (ugly) try/except block?

Thanks!

最满意答案

首先关于在numpy广播的简要说明。 当我从matlab切换到python时,广播对我来说有点令人困惑,但是一旦我花时间了解它,我意识到它可能是多么有用。 要了解有关广播的更多信息,请查看http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html ,

因为在numpy中广播一个(m,)数组(基本上与(1,m)数组或(1,1,m)数组等价),依此类推。 看起来你想让(m,)数组的行为像(m,1)数组一样。 我相信有时会发生这种情况,特别是在linalg模块中,但是如果你打算这样做,你应该知道你正在打破这种颠簸的惯例。

有了这个警告,有代码:

import scipy as sp def my_mean(x): if x.ndim == 1: x = x[:, sp.newaxis] m = sp.empty(x.shape) m[:] = x.mean(0) return sp.squeeze(m)

并举例说明:

In [6]: x = sp.arange(30).reshape(5,6) In [7]: x Out[7]: array([[ 0, 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22, 23], [24, 25, 26, 27, 28, 29]]) In [8]: my_mean(x) Out[8]: array([[ 12., 13., 14., 15., 16., 17.], [ 12., 13., 14., 15., 16., 17.], [ 12., 13., 14., 15., 16., 17.], [ 12., 13., 14., 15., 16., 17.], [ 12., 13., 14., 15., 16., 17.]]) In [9]: my_mean(x[0]) Out[9]: array([ 2.5, 2.5, 2.5, 2.5, 2.5, 2.5])

这比使用tile更快,时间如下:

In [1]: import scipy as sp In [2]: x = sp.arange(30).reshape(5,6) In [3]: m = x.mean(0) In [5]: timeit m_2d = sp.empty(x.shape); m_2d[:] = m 100000 loops, best of 3: 2.58 us per loop In [6]: timeit m_2d = sp.tile(m, (len(x), 1)) 100000 loops, best of 3: 13.3 us per loop

First A quick note about broadcasting in numpy. Broadcasting was kinda confusing to me when I switched over from matlab to python, but once I took the time to understand it I realized how useful it could be. To learn more about broadcasting take a look at http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html,

Because of broadcasting an (m,) array in numpy (what you're calling a vector) is essentially equivelent to an (1, m) array or (1, 1, m) array and so on. It seems like you want to have an (m,) array behave like a (m, 1) array. I believe this happens sometimes, especially in the linalg module, but if you're going to do it you should know that you're breaking the numpy convention.

With that warning there's the code:

import scipy as sp def my_mean(x): if x.ndim == 1: x = x[:, sp.newaxis] m = sp.empty(x.shape) m[:] = x.mean(0) return sp.squeeze(m)

and an example:

In [6]: x = sp.arange(30).reshape(5,6) In [7]: x Out[7]: array([[ 0, 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22, 23], [24, 25, 26, 27, 28, 29]]) In [8]: my_mean(x) Out[8]: array([[ 12., 13., 14., 15., 16., 17.], [ 12., 13., 14., 15., 16., 17.], [ 12., 13., 14., 15., 16., 17.], [ 12., 13., 14., 15., 16., 17.], [ 12., 13., 14., 15., 16., 17.]]) In [9]: my_mean(x[0]) Out[9]: array([ 2.5, 2.5, 2.5, 2.5, 2.5, 2.5])

This is faster than using tile, the timing is bellow:

In [1]: import scipy as sp In [2]: x = sp.arange(30).reshape(5,6) In [3]: m = x.mean(0) In [5]: timeit m_2d = sp.empty(x.shape); m_2d[:] = m 100000 loops, best of 3: 2.58 us per loop In [6]: timeit m_2d = sp.tile(m, (len(x), 1)) 100000 loops, best of 3: 13.3 us per loop

更多推荐

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

发布评论

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

>www.elefans.com

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