日安
我搜索过这个,但没有得到任何回应。我希望通过套接字发送一个多维numpy数组。因此,我决定将其转换为字符串:
但是,它会破坏数组的表示:
>>> import numpy as np
>>> x = np.array([[0, 1], [2, 3]])
>>> xstring = x.tostring()
>>> print xstring
>>> print x
[[0 1]
[2 3]]
>>> print xstring
>>> nparr = np.fromstring(xstring, dtype=np.uint8)
>>> print nparr
[0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0]
有没有办法把它转换成字符串,以某种方式,保存它的维数?
4条答案
按热度按时间fnx2tebb1#
试试这个例子:
在这个模型中,客户端向服务器发送多维ndarray。有两个函数startServer()和startClient()。startServer不接受任何参数,但startClient需要服务器地址和ndarray作为参数。首先启动服务器,然后启动客户端。服务器仅在收到客户端发出的关机消息后才开始从缓冲区阅读。
hk8txs482#
实际上,
.tostring
只返回原始数据。这意味着如果另一端不知道数组的形状和dtype,则还需要发送它们。也许使用Pickle序列化数组更容易:
但对于非常小的阵列,大小开销可能很大:
有关使用Pickle的更多信息,请访问see here.
q1qsirdb3#
这是一个使用XML-RPC的ajsp答案的临时答案。
在服务器端转换数据时,使用**'. tostring()'方法将numpy数据转换为字符串。这将numpy ndarray编码为bytes字符串。在客户端,当你接收到数据时,使用'. fromstring()'**方法对其进行解码。我为此写了两个简单的函数。希望这对你有帮助。
在接收端,数据作为**'xmlrpc.client. Binary'对象接收。您需要使用'.data**'访问数据。
**注意:**这种方法的唯一问题是XML-RPC在发送大型numpy数组时非常慢。我花了大约4秒来发送和接收一个(10,500,500,3)大小的numpy数组。
我用的是Python 3.7.4。
9njqaruj4#
我最近想做一件类似的事情,并试图自己做每件事,这占用了大量的时间和精力。事实证明,python中已经存在一个库,它可以为您做所有的事情(维护形状并抽象冗长的套接字代码)!
退房-https://pypi.org/project/mlsocket/