cvxopt.matrix 和 numpy.array 之间的 python3 转换



python: python3.2CVXOPT:1.1.5数字:1.6.1

我读了 http://abel.ee.ucla.edu/cvxopt/examples/tutorial/numpy.html

import cvxopt
import numpy as np
cvxopt.matrix(np.array([[7, 8, 9], [10, 11, 12]]))

我得到了

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: non-numeric element in list

np.array(cvxopt.matrix([[7, 8, 9], [10, 11, 12]])),我得到了

array([[b'x07', b'n'],
   [b'x08', b'x0b'],
   [b't', b'x0c']], 
  dtype='|S8')

截至cvxopt == 1.2.6年和numpy == 1.21.2年:

import cvxopt
import numpy as np
matrix = cvxopt.matrix(np.array([[7, 8, 9], [10, 11, 12]]))
print(matrix)

生成输出:

[  7   8   9]
[ 10  11  12]

print(repr(matrix)) 说:

<2x3 matrix, tc='i'>

print(type(matrix)) 说:

<class 'cvxopt.base.matrix'>

生成的矩阵具有整数类型('i'),因为起始数组numpy包含整数。从double开始,将生成'd'类型。

检查我在cvxopt论坛(https://groups.google.com/forum/?fromgroups=#!topic/cvxopt/9jWnkbJvk54)上发布的修补的dense.c。 用这个重新编译,你将能够将 np 数组转换为密集矩阵。 我认为稀疏矩阵需要相同的编辑,但由于我不需要它们,因此我将留给开发人员。

虽然它不是固定的,但一个简单的解决方法

cvxopt.matrix(nparray)

cvxopt.matrix(nparray.T.tolist())

相反的方向更难。如果你期望 int 数组,

np.vectorize(lambda x: int.from_bytes(x, 'big'))(np.array(cvxoptmat).T)

对于双精度数组:

import struct
np.vectorize(lambda x: struct.unpack('d', x))(np.array(cvxoptmat).T)

最新更新