2017-07-19 108 views
0

當試圖numpy的矩陣M寫入二進制文件爲:NumPy的不創建二進制文件

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 

我能知道如何解決這一問題?謝謝

+0

請先修復您的代碼(例如文件名)。 – patrick

+0

你忘了打開一個字符串。請先解決。 –

+0

哦!謝謝 。但仍然有相同的問題 – Medo

回答

1

您可以通過以下兩種等價方式之一進行:

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

1

替換:

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

M = Matrix.astype(np.float64) 

np.array(Matrix, dtype=np.float64)也將工作,但astype更簡單。

我在重新創建您的Matrix變量時遇到了一些問題。它的形狀是什麼?

np.save是將多維數組保存到文件的最佳方式。還有其他方法,但它們不保存形狀和dtype信息。


ndarray因爲第一(位置)參數應該是形狀,而不是另一個陣列是錯誤的。 buffer參數中提供了數據(如果有)。初學者或高級numpy用戶通常不會使用ndarray


什麼是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