2

从 Matlab 中导入这个数据文件scipy.io.loadmat后,一切似乎都很好,直到我们尝试计算其中一个矩阵的条件数。

这是为我们重现的最少代码量:

import scipy
import numpy

stuff = scipy.io.loadmat("dati-esercizio1.mat")
numpy.linalg.cond(stuff["A"])

这是 iPython 提供的扩展堆栈跟踪:

In [3]: numpy.linalg.cond(A)
---------------------------------------------------------------------------
LapackError                               Traceback (most recent call last)
/snip/<ipython-input-3-15d9ef00a605> in <module>()
----> 1 numpy.linalg.cond(A)

/snip/python2.7/site-packages/numpy/linalg/linalg.py in cond(x, p)
   1409     x = asarray(x) # in case we have a matrix
   1410     if p is None:
-> 1411         s = svd(x,compute_uv=False)
   1412         return s[0]/s[-1]
   1413     else:

/snip/python2.7/site-packages/numpy/linalg/linalg.py in svd(a, full_matrices, compute_uv)
   1313         work = zeros((lwork,), t)
   1314         results = lapack_routine(option, m, n, a, m, s, u, m, vt, nvt,
-> 1315                                  work, -1, iwork, 0)
   1316         lwork = int(work[0])
   1317         work = zeros((lwork,), t)

LapackError: Parameter a has non-native byte order in lapack_lite.dgesdd

所有明显的想法(如扁平化和重塑矩阵或从头开始重新创建矩阵,逐个元素重新分配它)都失败了。那么,为了使它更适合 numpy,我该如何处理数据呢?

4

3 回答 3

2

这是一个错误,前段时间修复:https ://github.com/numpy/numpy/pull/235

解决方法:

np.linalg.cond(stuff['A'].newbyteorder('='))
于 2012-10-29T20:55:01.690 回答
1

这对我有用:

In [33]: stuff = loadmat('dati-esercizio1.mat')

In [34]: a = stuff['A']

In [35]: try: np.linalg.cond(a)
   ....: except: print "Fail!"
Fail!

In [36]: b = np.array(a, dtype='>d')

In [37]: np.linalg.cond(b)
Out[37]: 62493201976.673141

In [38]: np.all(a == b)  # Verify they hold the same data.
Out[38]: True
于 2012-10-29T15:13:05.793 回答
-1

显然,结果 ndarray 中每个数字的字节顺序(字节序?)有问题,而不仅仅是 ndarray 对象本身。

像这样但更优雅的东西应该可以解决问题:

n, m = A.shape()
B = numpy.empty_like(A)

for i in xrange(n):
  for j in xrange(m):
    B[i,j] = float(A[i,j])

del A
B = A

print numpy.linalg.cond(A) # 62493210091.354507

(由于某种原因,就地替换仍然会给出该错误 - 所以整个对象的字节顺序也有问题。)

于 2012-10-29T14:06:20.280 回答