簡體   English   中英

如何解壓pkl文件?

[英]How to unpack pkl file?

我有一個來自 MNIST 數據集的 pkl 文件,它由手寫數字圖像組成。

我想看看這些數字圖像中的每一個,所以我需要解壓 pkl 文件,但我不知道如何解壓。

有沒有辦法解壓/解壓 pkl 文件?

一般來說

您的pkl文件實際上是一個序列化的pickle文件,這意味着它已使用 Python 的pickle模塊轉儲。

要取消腌制數據,您可以:

import pickle


with open('serialized.pkl', 'rb') as f:
    data = pickle.load(f)

對於 MNIST 數據集

注意gzip僅在文件被壓縮時才需要:

import gzip
import pickle


with gzip.open('mnist.pkl.gz', 'rb') as f:
    train_set, valid_set, test_set = pickle.load(f)

每組可以進一步划分(即訓練集):

train_x, train_y = train_set

這些將是您的集合的輸入(數字)和輸出(標簽)。

如果要顯示數字:

import matplotlib.cm as cm
import matplotlib.pyplot as plt


plt.imshow(train_x[0].reshape((28, 28)), cmap=cm.Greys_r)
plt.show()

mnist_digit

另一種選擇是查看原始數據:

http://yann.lecun.com/exdb/mnist/

但這會更難,因為您需要創建一個程序來讀取這些文件中的二進制數據。 所以我建議你使用 Python,並使用pickle加載數據。 如您所見,這非常容易。 ;-)

方便的單線

pkl() (
  python -c 'import pickle,sys;d=pickle.load(open(sys.argv[1],"rb"));print(d)' "$1"
)
pkl my.pkl

將為腌制對象打印__str__

可視化對象的一般問題當然是未定義的,因此如果__str__不夠,您將需要一個自定義腳本。

如果您想使用原始 MNIST 文件,這里是您可以反序列化它們的方法。

如果您尚未下載文件,請先在終端中運行以下命令:

wget http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz
wget http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz
wget http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz
wget http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz

然后將以下內容另存為deserialize.py並運行它。

import numpy as np
import gzip

IMG_DIM = 28

def decode_image_file(fname):
    result = []
    n_bytes_per_img = IMG_DIM*IMG_DIM

    with gzip.open(fname, 'rb') as f:
        bytes_ = f.read()
        data = bytes_[16:]

        if len(data) % n_bytes_per_img != 0:
            raise Exception('Something wrong with the file')

        result = np.frombuffer(data, dtype=np.uint8).reshape(
            len(bytes_)//n_bytes_per_img, n_bytes_per_img)

    return result

def decode_label_file(fname):
    result = []

    with gzip.open(fname, 'rb') as f:
        bytes_ = f.read()
        data = bytes_[8:]

        result = np.frombuffer(data, dtype=np.uint8)

    return result

train_images = decode_image_file('train-images-idx3-ubyte.gz')
train_labels = decode_label_file('train-labels-idx1-ubyte.gz')

test_images = decode_image_file('t10k-images-idx3-ubyte.gz')
test_labels = decode_label_file('t10k-labels-idx1-ubyte.gz')

該腳本不會像腌制文件中那樣標准化像素值。 要做到這一點,你所要做的就是

train_images = train_images/255
test_images = test_images/255

需要使用pickle (如果文件被壓縮,則為gzip )模塊

注意:這些已經在標准 Python 庫中。 無需安裝任何新東西

暫無
暫無

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

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