簡體   English   中英

如何將ndarray寫入python中的文本文件?

[英]How to write the ndarray to text file in python?

我正在嘗試使用MNIST數據進行研究,現在數據集描述為:

training_data作為具有兩個條目的元組返回。 第一個條目包含實際的訓練圖像。 這是一個具有50,000個條目的numpy ndarray。 每個條目依次是一個具有784個值的numpy ndarray,代表單個MNIST圖像中的28 * 28 = 784個像素。

 The second entry in the ``training_data`` tuple is a numpy ndarray containing 50,000 entries. Those entries are just the digit values (0...9) for the corresponding images contained in the first entry of the tuple. 

現在我正在像這樣轉換訓練數據:

特別地, training_data是包含50,000個2元組(x, y) x是一個包含輸入圖像的784維numpy.ndarray。 y是一個10維numpy.ndarray,它表示與x的正確數字相對應的單位向量。 的代碼是:

def load_data_nn():
    training_data, validation_data, test_data = load_data()
    #print training_data[0][1]
    #inputs = [np.reshape(x, (784, 1)) for x in training_data[0]]
    inputs = [np.reshape(x, (784,1)) for x in training_data[0]]
    print inputs[0]
    results = [vectorized_result(y) for y in training_data[1]]
    training_data = zip(inputs, results)
    test_inputs = [np.reshape(x, (784, 1)) for x in test_data[0]]
    return (training_data, test_inputs, test_data[1])

現在,我要將輸入寫入文本文件,這意味着一行將是inputs [0],另一行是inputs [1],inputs [0]內部的數據將以空格分隔,並且不存在任何ndarray括號。例:

 0 0.45 0.47 0,76

 0.78 0.34 0.35 0.56

這是文本文件中的一行輸入[0]。如何將ndarray轉換為上面的文本文件?

由於您問題的答案似乎很簡單,我想您的問題是速度。 幸運的是,我們可以在這里使用多重處理。 嘗試這個:

from multiprocessing import Pool

def joinRow(row):
    return ' '.join(str(cell) for cell in row)

def inputsToFile(inputs, filepath):
    # in python3 you can do:
    # with Pool() as p:
    #     lines = p.map(joinRow, inputs, chunksize=1000)
    # instead of code from here...
    p = Pool()
    try:
        lines = p.map(joinRow, inputs, chunksize=1000)
    finally:
        p.close()
    # ...to here. But this works for both.

    with open(filepath,'w') as f:
        f.write('\n'.join(lines)) # joining already created strings goes fast

在我骯臟的筆記本電腦上仍然需要一段時間,但比僅輸入'\\n'.join(' '.join(str(cell) for cell in row) for row in inputs)快得多'\\n'.join(' '.join(str(cell) for cell in row) for row in inputs)

順便說一句,您也可以加快其余代碼的速度:

def load_data_nn():
    training_data, validation_data, test_data = load_data()
    # suppose training_data[0].shape == (50000,28,28), otherwise leave it as is
    inputs = training_data[0].reshape((50000,784,1))
    print inputs[0]
    # create identity matrix and use entries of training_data[1] to
    # index corresponding unit vectors
    results = np.eye(10)[training_data[1]]
    training_data = zip(inputs, results)
    # suppose test_data[0].shape == (50000,28,28), otherwise leave it as is
    test_inputs = test_data[0].reshape((50000,784,1))
    return (training_data, test_inputs, test_data[1])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM