小编Sau*_*tro的帖子

numpy.sum可能比Python for循环慢

在特定轴上求和数组时,专用数组方法array.sum(ax)实际上可能比for循环慢:

v = np.random.rand(3,1e4)

timeit v.sum(0)                             # vectorized method
1000 loops, best of 3: 183 us per loop

timeit for row in v[1:]: v[0] += row        # python loop
10000 loops, best of 3: 39.3 us per loop
Run Code Online (Sandbox Code Playgroud)

矢量化方法比普通的for循环慢4倍!这里(g)的内容(wr),我不能相信numpy中的矢量化方法比for循环更快吗?

python performance numpy vectorization

7
推荐指数
1
解决办法
2949
查看次数

函数矩阵,SymPy和SciPy的数值积分

从我的SymPy输出我有下面显示的矩阵,我必须在2D中集成.目前我正在以元素方式进行,如下所示.此方法适用,但它变得太慢(用于sympy.mpmath.quadscipy.integrate.dblquad)为我的真实案例(其中A,其职能是更大(见下面编辑):

from sympy import Matrix, sin, cos
import sympy
import scipy
sympy.var( 'x, t' )
A = Matrix([[(sin(2-0.1*x)*sin(t)*x+cos(2-0.1*x)*cos(t)*x)*cos(3-0.1*x)*cos(t)],
            [(cos(2-0.1*x)*sin(t)*x+sin(2-0.1*x)*cos(t)*x)*sin(3-0.1*x)*cos(t)],
            [(cos(2-0.1*x)*sin(t)*x+cos(2-0.1*x)*sin(t)*x)*sin(3-0.1*x)*sin(t)]])

# integration intervals
x1,x2,t1,t2 = (30, 75, 0, 2*scipy.pi)

# element-wise integration
from sympy.utilities import lambdify
from sympy.mpmath import quad
from scipy.integrate import dblquad
A_int1 = scipy.zeros( A.shape, dtype=float )
A_int2 = scipy.zeros( A.shape, dtype=float )
for (i,j), expr in scipy.ndenumerate(A):
    tmp = lambdify( (x,t), expr, 'math' )
    A_int1[i,j] = quad( tmp, (x1, x2), …
Run Code Online (Sandbox Code Playgroud)

python symbolic-math sympy scipy numerical-integration

7
推荐指数
1
解决办法
1924
查看次数

numpy.genfromtxt:不明确的分隔符?

我正在尝试编写一个通用脚本,其中一部分导入以逗号分隔或以空格分隔的文件.我希望脚本识别任何一种类型.有没有办法指定类似的东西

arrayobj = np.genfromtxt(file.txt, delimiter=(',' OR '\t'), names=None, dtype=None)
Run Code Online (Sandbox Code Playgroud)

我尝试使用正则表达式(',|\t'),但这也不起作用.

python numpy delimiter genfromtxt

7
推荐指数
1
解决办法
1640
查看次数

重新排列点列表以达到它们之间的最短距离

我有一个2D点列表,例如:

1,1 2,2 1,3 4,5 2,1
Run Code Online (Sandbox Code Playgroud)

这些点之间的距离是已知的(例如,使用math.hypot.)我想对列表进行排序,以便它们之间有最小距离.我可以使用任何可能的解决方案订单,只要这些点是最短的顺序.

实现这一目标的最pythonic方法是什么?

我正在考虑计算任何项目和任何其他项目之间的距离,并且每次都选择最小的项目,但这对我正在处理的列表来说是一个缓慢的算法(1,000项并不罕见.)

python sorting algorithm list

7
推荐指数
1
解决办法
3223
查看次数

数组和向量的numpy元素乘法

我想做这样的事情:

a =  # multi-dimensional numpy array
ares = # multi-dim array, same shape as a
a.shape
>>> (45, 72, 37, 24)  # the relevant point is that all dimension are different
v = # 1D numpy array, i.e. a vector
v.shape
>>> (37)  # note that v has the same length as the 3rd dimension of a
for i in range(37):
    ares[:,:,i,:] = a[:,:,i,:]*v[i]
Run Code Online (Sandbox Code Playgroud)

我认为必须有一个更紧凑的方式来做这个numpy,但我还没弄明白.我想我可以复制v然后计算a*v,但我猜测还有更好的东西.所以我需要"在一个给定的轴上"进行元素智能乘法,可以这么说.谁知道我怎么做到这一点?谢谢.(顺便说一下,我确实发现了一个非常复杂的问题,但由于OP在那里的特殊问题的性质,讨论非常简短,并被追踪到其他问题.)

python arrays numpy

7
推荐指数
3
解决办法
7473
查看次数

"AttributeError:'list'对象没有属性'ravel'"

我有一个微分方程系统,需要计算雅可比矩阵.下面的代码抛出AttributeError: 'list' object has no attribute 'ravel'.我错过了什么?

import numpy as np
import numdifftools as ndt

def rhs(z, t=0):
    x,y = z

    xdot = (x/5 + y)*(-x**2+1)
    ydot = -x*(-y**2+1)

    return [xdot, ydot]

Jfun = ndt.Jacobian(rhs)

Jfun([1,1])
Run Code Online (Sandbox Code Playgroud)

python numpy list

7
推荐指数
1
解决办法
6322
查看次数

python matplotlib图稀疏矩阵模式

给定一个稀疏的二进制矩阵A(csr,coo,等等)我想制作一个图,这样我可以看到图中的位置(i,j)= white,如果A(i,j)= 1,和(i, j)= A,如果A(i,j)= 0;

对于密集的numpy数组,matshow将完成这项工作.但是,我的稀疏矩阵(例如100000 x 1000000)的维度很大,可以转换为密集阵列.我想知道如何在稀疏矩阵中绘制模式.

谢谢

python numpy matplotlib scipy sparse-matrix

7
推荐指数
2
解决办法
1万
查看次数

如何在scipy中创建一个巨大的稀疏矩阵

我正在尝试创建一个非常庞大的稀疏矩阵,它具有一个形状(447957347, 5027974).并且,它包含3,289,288,566个元素.

但是,当我创建一个csr_matrix使用时scipy.sparse,它会返回如下内容:

<447957346x5027974 sparse matrix of type '<type 'numpy.uint32'>'
    with -1005678730 stored elements in Compressed Sparse Row format>
Run Code Online (Sandbox Code Playgroud)

创建矩阵的源代码是:

indptr = np.array(a, dtype=np.uint32)    # a is a python array('L') contain row index information
indices = np.array(b, dtype=np.uint32)   # b is  a python array('L') contain column index information
data = np.ones((len(indices),), dtype=np.uint32)
test = csr_matrix((data,indices,indptr), shape=(len(indptr)-1, 5027974), dtype=np.uint32)
Run Code Online (Sandbox Code Playgroud)

而且,我还发现当我将一个30亿长度的python数组转换为numpy数组时,它会引发一个错误:

ValueError:setting an array element with a sequence
Run Code Online (Sandbox Code Playgroud)

但是,当我创建三个10亿个长度的python数组,并将它们转换为numpy数组时,然后追加它们.它工作正常.

我糊涂了.

python arrays numpy scipy sparse-matrix

7
推荐指数
1
解决办法
1096
查看次数

如何将numpy.argpartition的输出应用于二维数组?

我有一个较大的2d numpy数组,我想提取每行的最低10个元素及其索引.由于我的数组很大,我宁愿不对整个数组进行排序.

我听说过这个argpartition()函数,我可以用它获得最低10个元素的索引:

top10indexes = np.argpartition(myBigArray,10)[:,:10]
Run Code Online (Sandbox Code Playgroud)

请注意,argpartition()默认情况下分区轴为-1,这就是我想要的.此处的结果与myBigArray具有相同的形状,其中包含各个行的索引,使得前10个索引指向10个最低值.

我现在如何提取myBigArray与这些索引相对应的元素?

明显的花哨索引喜欢myBigArray[top10indexes]myBigArray[:,top10indexes]做一些完全不同的事情.我还可以使用列表推导,例如:

array([row[idxs] for row,idxs in zip(myBigArray,top10indexes)])
Run Code Online (Sandbox Code Playgroud)

但这会导致性能损失迭代numpy行并将结果转换回数组.

nb:我可以np.partition()用来获取值,它们甚至可能对应于索引(或者可能不是......),但如果我可以避免它,我不想再进行两次分区.

python arrays indexing performance numpy

7
推荐指数
1
解决办法
2598
查看次数

将一列零添加到csr_matrix

我有一个MxN稀疏csr_matrix,我想在矩阵的右边添加一些只有零的列.原则上,阵列indptr,indicesdata保持相同的,所以我只是想改变矩阵的尺寸.但是,这似乎没有实现.

>>> A = csr_matrix(np.identity(5), dtype = int)
>>> A.toarray()
array([[1, 0, 0, 0, 0],
       [0, 1, 0, 0, 0],
       [0, 0, 1, 0, 0],
       [0, 0, 0, 1, 0],
       [0, 0, 0, 0, 1]])
>>> A.shape
(5, 5)
>>> A.shape = ((5,7))
NotImplementedError: Reshaping not implemented for csr_matrix.
Run Code Online (Sandbox Code Playgroud)

水平堆叠零矩阵似乎也不起作用.

>>> B = csr_matrix(np.zeros([5,2]), dtype = int)
>>> B.toarray()
array([[0, 0],
       [0, 0],
       [0, 0],
       [0, 0],
       [0, 0]])
>>> np.hstack((A,B))
array([ …
Run Code Online (Sandbox Code Playgroud)

python numpy scipy sparse-matrix

7
推荐指数
2
解决办法
3507
查看次数