【问题标题】:Numpy does not create binary fileNumpy 不创建二进制文件
【发布时间】:2017-12-24 21:11:51
【问题描述】:

当尝试将 numpy 矩阵 M 写入二进制文件时:

from io import open
X = [random.randint(0, 2 ** self.stages - 1)for _ in range(num)]
Matrix = np.asarray([list(map(int, list(x))) for x in X])

file_output = open('result.bin', 'wb')
M = np.ndarray(Matrix, dtype=np.float64)
file_output.write(M)
file_output.close()

我收到此错误:

Traceback (most recent call last):
  File "experiments.py", line 164, in <module>
    write_data(X, y)
  File "experiments.py", line 39, in write_data
    arr = np.ndarray(Matrix, dtype=np.float64)
ValueError: sequence too large; cannot be greater than 32

我能知道如何解决这个问题吗?谢谢

【问题讨论】:

  • 请先修复您的代码(例如文件名)。
  • 您忘记打开一个字符串。请先解决这个问题。
  • 哦!谢谢你 。但还是有同样的问题
  • arr = np.ndarray(Matrix, dtype=np.float64)出现错误。我们需要知道Matrix 是什么。请创建一个minimal, complete and verifiable example
  • 看来问题在于使用np.ndarraythis问题的答案建议不要使用它,而是使用np.array

标签: python numpy


【解决方案1】:

替换:

M = np.ndarray(Matrix, dtype=np.float64)

M = Matrix.astype(np.float64)

np.array(Matrix, dtype=np.float64) 也可以,但astype 更简单。

我在重新创建 Matrix 变量时遇到了一些问题。它的形状是什么?

np.save 是将多维数组保存到文件的最佳方式。还有其他方法,但它们不保存 shape 和 dtype 信息。


ndarray 是错误的,因为第一个(位置)参数应该是形状,而不是另一个数组。 buffer 参数中提供了数据(如果有)。 ndarray 通常不被初学者甚至高级 numpy 用户使用。


Matrix 应该是什么。当我使用几个参数尝试您的代码时,map 步骤中出现错误:

In [495]: X = [np.random.randint(0, 2 ** 2 - 1)for _ in range(4)]
     ...: Matrix = np.asarray([list(map(int, list(x))) for x in X])
     ...: 
-----> 2 Matrix = np.asarray([list(map(int, list(x))) for x in X])
....
TypeError: 'int' object is not iterable
In [496]: X
Out[496]: [1, 2, 1, 0]

X 只是一个数字列表吗?不是某种数组列表?为什么是Matrix 步骤?它是否试图将列表的嵌套列表转换为整数?即使randint 已经创建了整数?然后你转换为float?

【讨论】:

    【解决方案2】:

    您可以通过两种等效方式之一来执行此操作:

    import numpy as np
    
    a = np.random.normal(size=(10,10))
    a.tofile('test1.dat')
    
    with open('test2.dat', 'wb') as f:
        f.write(a.tobytes())
    
    # diff test1.dat test2.dat
    

    请参阅tofile 的文档。但是,从原始示例来看,Matrix 似乎无法转换为 ndarray

    【讨论】:

      猜你喜欢
      • 2020-08-03
      • 2014-11-13
      • 1970-01-01
      • 1970-01-01
      • 2014-04-08
      • 2017-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多